In my React Native app, I have <Text> items that on some phones overflow and take up two lines. Is it possible to adjust the fontSize dynamically to make sure the text fits in one line?
Yes. You can use pixelratio and dimensions from react native Use it as below
import { Dimensions, Platform, PixelRatio } from 'react-native';
const {
  width: SCREEN_WIDTH,
  height: SCREEN_HEIGHT,
} = Dimensions.get('window');
//use your testing phone width to replace 320
const scale = SCREEN_WIDTH / 320;
export function normalize(size) {
  const newSize = size * scale 
  if (Platform.OS === 'ios') {
    return Math.round(PixelRatio.roundToNearestPixel(newSize))
  } else {
    return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
  }
}
For the box style, use the above method as follows.
const styles = {
  textStyle: {
    fontSize: normalize(12),
  },
};
Above method is more accurate when you want to dynamically change the font size.
But if you only want to fit the text to a single line you can also use adjustsFontSizeToFit as follows
<View>
  <Text
    numberOfLines={1}
    adjustsFontSizeToFit
    style={{textAlign:'center',fontSize:50}}
  >
    YOUR_TEXT_HERE
  </Text>
</View>
Possibly the oft-used prop in React Native to scale down the font size automatically according to given parent component width and height is adjustsFontSizeToFit.
<View>
    <Text style={styles.text} numberOfLines={1} adjustsFontSizeToFit>
</View>
numberOfLines={1} defines how many lines we want to display on screen. And in the above case, it is just 1.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With