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?
Asked
Active
Viewed 4,651 times
3

gkeenley
- 6,088
- 8
- 54
- 129
2 Answers
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
-
Hi Ishara, why do you subtract 2 from the returned value for Android? – gkeenley May 14 '20 at 18:41
-
Hi, Its not a must. It was a slight adjustment for my UI. For your app its not a must. You can use without it . – Ishara Sandun May 15 '20 at 16:05
-
1`adjustsFontSizeToFit` – benmneb Sep 09 '22 at 07:01
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