DEV Community

Discussion on: My React Native Stack After 1 Year

Collapse
aore profile image
Emmanuel Oreoluwa

How do I make ur react native app stable on different screen size
My react native app on my emulator is okay but when I test it on a smaller screen size the soon doesn't fit the screen

Collapse
newbiebr profile image
Arthur Dao Author • Edited on

Hi. You are right, I don't know how I can forgot to talk about responsiveness. I will update that soon on my repository. Here are what I do to handle that:

  • Avoid as much as I can "absolute" position, hard values (100, 300, 1680,...) especially for big ones.
  • Instead, I use flex, and % values
  • I have this normalize function for adapting hard values accordingly to the screen's width or height. I might upload it on the repository later:
import { Dimensions, Platform, PixelRatio } from 'react-native';

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

// based on iphone X's scale
const wscale = SCREEN_WIDTH / 375;
const hscale = SCREEN_HEIGHT / 812;

export function normalize(size, based = 'width') {
  const newSize = based === 'height' ? size * hscale : size * wscale;
  if (Platform.OS === 'ios') {
    return Math.round(PixelRatio.roundToNearestPixel(newSize));
  } else {
    return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2;
  }
}

So now I can use:

// iphone X
normalize(100) // = 100

// iphone 5s
normalize(100) // = maybe 80

// You can choose either "width" (default) or "height" depend on cases:
container = {
  width: normalize(100, "width"), // "width" is optional, it's default
  height: normalize(100, "height")
}
  • Before pushing, I test my work on 3 differents emulators: iphone5s (small), iphone 8 (medium) and iphone Xs Max (big)

Hope this help :D