reactjs – How to adjust font size to fit view in React Native for Android?-ThrowExceptions

Exception or error:

How I can make the font size of the text auto change inside a view in react native?

I have text with different lengths, some of which doesn’t fit the view so decreased the font size. I have checked the docs and found this
but it’s for iOS only and I need it for Android.

And does it work with other components like button and touchableopacity?

How to solve:

A bit improved Jeffy Lee code worked for me

const AdjustLabel = ({
  fontSize, text, style, numberOfLines
}) => {
  const [currentFont, setCurrentFont] = 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>
  );
};

###

Try this approach. Consider setting the font size according to screen width as following

width: Dimensions.get('window').width

So in your style try to make a percentage calculation to make the font size fit the screen

style={
  text:{
     fontSize:0.05*width
  }
}

this will gonna work for all screens (both Android and IOS)

###

I had a similar issue with the number of text resizing the views (user inputs string into an input field currently limited to 30 characters) in my React Native app. I noticed there are a few properties already implemented for iOS: adjustsFontSizeToFit minimumFontScale={.4} however the Android does not have such methods available at this time.

Note: Solution which works for me but might not be the “best” possible!

Currently, I’m using a nested ternary operator:

fontSize: this.props.driverName.length > 12 && 
this.props.driverName.length < 20 ? heightPercentageToDP('2%') : 
this.props.driverName.length > 20 && this.props.driverName.length < 40 
? heightPercentageToDP('1.75%') : heightPercentageToDP('2.25%')

In layman’s terms, the above ternary checks the range of characters used and based off the range modifies the fontSize into a ‘%’ inside the view. The method: heightPercentageToDP is a function which I am using to convert the size into a ‘%’ based on the mobile screen’s DP (this way it is responsive on a tablet or a mobile phone).

heightPercentageToDP Code Snippet:

    import { Dimensions, PixelRatio } from "react-native";
    const widthPercentageToDP = widthPercent => {
    const screenWidth = Dimensions.get("window").width;
    // Convert string input to decimal number
    const elemWidth = parseFloat(widthPercent);
    return PixelRatio.roundToNearestPixel((screenWidth * elemWidth) / 100);
    };
    const heightPercentageToDP = heightPercent => {
    const screenHeight = Dimensions.get("window").height;
    // Convert string input to decimal number
    const elemHeight = parseFloat(heightPercent);
    return PixelRatio.roundToNearestPixel((screenHeight * elemHeight) / 100);
    };
    export { widthPercentageToDP, heightPercentageToDP };

Credit and source for heightPercentageToDP goes to:
https://medium.com/react-native-training/build-responsive-react-native-views-for-any-device-and-support-orientation-change-1c8beba5bc23.

###

Without and headache you can use a small library which can maintain the font scale for each device.

npm i --save react-native-responsive-fontsize

import RF from “react-native-responsive-fontsize”

fontSize: RF(2)

But don’t forget to add allowFontScaling={false} props to text. Because ios has auto fon scaling ability so font size could be different from your expectations sometimes.

###

Try this method.

I used the method onLayout to achieve this.

First, I wrapped my Text view inside a fixed size View, then I implement onLayout for both view, so that I can get the height of the fixed size View and the height of the Text view.

Next, if the Text view’s required height is more than the height of our View, we decrease the font size of our Text view until the height can fit into our View.

Herein the test code, I made 2 Views, one in pink and one in yellow background, the font size of Text inside the pink View will be adjust to fit the View and the yellow Text will remain the same font size.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const [size, setSize] = useState(20)
  const [viewHeight, setViewHeight] = useState(0)
  const [textHeight, setTextHeight] = useState(0)

  useEffect(() => {
    if (textHeight > viewHeight) {
      setSize(size - 1) // <<< You may adjust value 1 to a smaller value so the text can be shrink more precisely
    }
  }, [textHeight])

  return (
    <View style={styles.container}>
      <View
        style={{
          margin: 20,
          backgroundColor: 'pink',
          width: 200,
          height: 200
        }}
        onLayout={(event) => {
          var { x, y, width, height } = event.nativeEvent.layout;
          setViewHeight(height)
        }}
      >
        <Text
          style={{
            fontSize: size,
          }}
          onLayout={(event) => {
            var { x, y, width, height } = event.nativeEvent.layout;
            setTextHeight(height)
          }}
        >
          Gemma is a middle grade novel that follows a curious explorer and her ring-tailed lemur, Milo, 
          as they hunt for the “most greatest treasure in the world”. Solving riddles, battling a bell-wearing 
          jaguar, and traveling the Eight Seas, Gemma’s adventures take her from a young girl to a brave captain, 
          whose only limits are the stars.
        </Text>
      </View>

      <View
        style={{
          margin: 20,
          backgroundColor: 'yellow',
          width: 200,
          height: 200
        }}
      >
        <Text
          style={{
            fontSize: 20
          }}
        >
          Gemma is a middle grade novel that follows a curious explorer and her ring-tailed lemur, Milo, 
          as they hunt for the “most greatest treasure in the world”. Solving riddles, battling a bell-wearing 
          jaguar, and traveling the Eight Seas, Gemma’s adventures take her from a young girl to a brave captain, 
          whose only limits are the stars.
        </Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

You may notice the pink Text’s font is having a shrinking animation when the font size is decreasing, I suggest that you can initial the Text opacity with 0 and after the font adjustment finish set it to 1 so user wont see the ugly animation.

Leave a Reply

Your email address will not be published. Required fields are marked *