sam
sam

Reputation: 11

Handle different Screens in React Native

I'm an android developer and I'm new to react-native. Can anyone help me in understanding how to handle multiple screen sizes and orientation changes in android and ios phones in react native? Thanks!

Upvotes: 0

Views: 1223

Answers (2)

Haseeb A
Haseeb A

Reputation: 6152

React native's Dimensions module is used for this. https://reactnative.dev/docs/dimensions

import { Dimensions } from 'react-native';

// Always call Dimensions only inside the function/class. The value could change otherwise.

const windowWidth = Dimensions.get('window').width; // Window width
const windowHeight = Dimensions.get('window').height; //Window height

const windowWidth = Dimensions.get('screen').width; //Screen height
const windowHeight = Dimensions.get('screen').height; //Screen width

//To listen to changes
Dimensions.addEventListener('change', (e) => {
  const { width, height } = e.window;
  //Then just use it. 🙃
})

For orientation detection check https://adrianhall.github.io/react%20native/2017/07/26/handling-orientation-changes-in-react-native/

Upvotes: 0

wentris
wentris

Reputation: 513

first of all you can check your device by Platform

import {Platform} from 'react-native';

{
  "OS": "ios",
  "Version": "14.0",
  "__constants": {
    "forceTouchAvailable": false,
    "interfaceIdiom": "phone",
    "isTesting": false,
    "osVersion": "14.0",
    "reactNativeVersion": { "major": 0, "minor": 61, "patch": 5 },
    "systemName": "iOS",
  },
  "constants": {
    "forceTouchAvailable": false,
    "interfaceIdiom": "phone",
    "isTesting": false,
    "osVersion": "14.0",
    "reactNativeVersion": { "major": 0, "minor": 61, "patch": 5 },
    "systemName": "iOS",
  },
  "isPad": false,
  "isTV": false,
  "isTVOS": false,
  "isTesting": false,
  "select": [Function select],
}

then you can check dimensions from your components by hook useWindowDimensions

{"fontScale": 1, "height": 896, "scale": 2, "width": 414}

or Dimensions - which you can use at any place in your App

import {Dimensions} from 'react-native';

const dimensions = Dimensions.get('screen');

then just compare width and height.

also if you need to handle orientation changing you may use lib like this react-native-orientation

Upvotes: 1

Related Questions