How to adjust font size to fit view in React Native for Android?

Sometimes, we want to adjust font size to fit view in React Native for Android.

In this article, we’ll look at how to adjust font size to fit view in React Native for Android.

How to adjust font size to fit view in React Native for Android?

To adjust font size to fit view in React Native for Android, we can adjust the font size to fit the text onto the number of lines.

For instance, we write:

import * as React from 'react';
import { View, Text } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const AdjustLabel = ({ fontSize, text, style, numberOfLines }) => {
  const [currentFont, setCurrentFont] = React.useState(fontSize);

  return (
    <Text
      numberOfLines={numberOfLines}
      adjustsFontSizeToFit
      style={[style, { fontSize: currentFont }]}
      onTextLayout={(e) => {
        const { lines } = e.nativeEvent;
        if (lines.length > numberOfLines) {
          setCurrentFont(currentFont - 1);
        }
      }}>
      {text}
    </Text>
  );
};

export default function App() {
  return (
    <View style={{ overflow: 'hidden', paddingBottom: 5 }}>
      <AdjustLabel
        text="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
        fontSize={50}
        numberOfLines={2}
      />
    </View>
  );
}

to create the AdjustLabel component that has the adjustsFontSizeToFit prop and also calculates the font size in the onTextLayout callback.

We calculate the font size in the callback by getting lines.length from the event.

Then we adjust the font if lines.length is bigger than numberOfLines.

And we set the fontSize to currentFont to change the font size.

Conclusion

To adjust font size to fit view in React Native for Android, we can adjust the font size to fit the text onto the number of lines.