Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
gkeenley Avatar asked Oct 29 '25 08:10

gkeenley


2 Answers

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>
like image 87
Ishara Sandun Avatar answered Oct 30 '25 23:10

Ishara Sandun


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.

like image 21
yansusanto Avatar answered Oct 30 '25 23:10

yansusanto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!