Sometimes, we want to set responsive font size with React Native.
In this article, we’ll look at how to set responsive font size with React Native.
How to set responsive font size with React Native?
To set responsive font size with React Native, we can use the Dimensions
object to get the values to calculate the font size.
For instance, we write:
import * as React from 'react';
import { View, Text, Dimensions, Platform, PixelRatio } from 'react-native';
import { Card } from 'react-native-paper';
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');
const scale = SCREEN_WIDTH / 320;
const normalize = (size) => {
const newSize = size * scale;
if (Platform.OS === 'ios') {
return Math.round(PixelRatio.roundToNearestPixel(newSize));
} else {
return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2;
}
};
const App = () => {
return (
<View>
<Text style={{ fontSize: normalize(30) }}>hello</Text>
</View>
);
};
export default App;
to define the normalize
function that calculates newSize
by multipklying size and
scale`.
We get the scale
by dividing SCREEN_WIDTH
by a number.
Then we return the actual font size depending on the platform.
We use PixelRatio.roundToNearestPixel
to round to the nearest pixel.
Finally. we set the fontSize
of the Text
.
Conclusion
To set responsive font size with React Native, we can use the Dimensions
object to get the values to calculate the font size.