reactjsreact-nativeword-wrapreact-native-text

React Native: is it possible to adjust fontSize to make sure font fits in one line?


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?


Solution

  • 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>