React-native responsive font size

john doe picture john doe · Jul 19, 2019 · Viewed 7.3k times · Source

I am developing a tablet app (Android and iOS) with Expo and React-Native.

I managed to make the layout responsive without getting into any problems. After running the app on different size devices, i noticed that i forgot about font size responsiveness.

I tried every npm library that i could find ( react-native-responsive-fontsize, react-native-cross-platform-responsive-dimensions, react-native-responsive-fontsize ). With any one of these, I ran out to the same problem: at app's startup, based on device's orientation, font size renders different. (ie. if I open the app when holding the device in portrait mode, font size is visibly bigger compared to when I open the app when holding the device in landscape mode - landscape mode being my app's default orientation). I tried to lock my app's screen orientation on landscape at startup and that reset it to default after my first component is mounted, but that also didn't help.

I came to the conclusion that this happens because all those libraries are using device's dimensions to make procentual values of what I pass to them, but only referring to only one dimension (width or height), which are different based on initial device orientation.

I tried to implement my own solution, thinking about something that would base on both width and height, not on only one of them, and I had come out with this function:

const height = Dimensions.get('window').height;
const width = Dimensions.get('window').width;

export function proportionalSize(size) {
     let aspectRatioSize = width * height;
     let aspectRatioUnit = aspectRatioSize * 0.00001;

     return parseFloat(size) * 0.1 * aspectRatioUnit;
}

This works only on the device on which I develop the app...font sizes will not keep the same proportions on other devices with different screen size.

I lost enough days modifying font sizes from my entire code, trying to switch between libraries. Do you have any ideas of how can i get over this, or what am I missing? I initially taught that will be my smallest problem, but I was wrong.

Later edit: I noticed that my problem goes away after reloading the app. It happens only at the first render, and after reloading, font-size works just fine.

Answer

vishu2124 picture vishu2124 · Jul 19, 2019

you can use this function

import { Dimensions, Platform, PixelRatio } from 'react-native';

const {
  width: SCREEN_WIDTH,
  height: SCREEN_HEIGHT,
} = Dimensions.get('window');

// based on iphone 5s's scale
const scale = SCREEN_WIDTH / 320;

export function actuatedNormalize(size) {
  const newSize = size * scale
  if (Platform.OS === 'ios') {
    return Math.round(PixelRatio.roundToNearestPixel(newSize))
  } else {
    return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
  }
}

and use

fontSize: actuatedNormalize(12)