3

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?

gkeenley
  • 6,088
  • 8
  • 54
  • 129

2 Answers2

3

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>
Ishara Sandun
  • 699
  • 1
  • 7
  • 13
2

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.

yansusanto
  • 355
  • 1
  • 6
  • 13