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 decrea
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.