Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the useful height of an iOS device in React Native?

In some very specific cases I need to set the height of a View to the full height of the device useful area (without using flex).

I was using a hardcoded "notch height" to calculate this useful height but I just discovered that the notch can have different heights depending on the device. (3 points of difference between iPhone XS and iPhone XS Max).

Is there a way to know the useful height of a device with notch and safe area?

like image 241
jphorta Avatar asked Nov 15 '18 12:11

jphorta


People also ask

How do I get the device height in React Native?

You can get the application window's width and height using the following code: const windowWidth = Dimensions. get('window').

How do you use height in React Native?

In react native application, to set the dimensions of a component, we use width and height properties. Remember, all the values of dimensions are unitless like we can't use height: 20px to set the height of a component instead of we just use height: 20 and react-native automatically set the pixels.

How do you find device width and height in react?

To get the width and height of the window in React:Use the innerWidth and innerHeight properties on the window object. Add an event listener for the resize event in the useEffect hook. Keep changes to the width and height of the window in a state variable.


2 Answers

use 'react-native-safe-area-context'

https://www.npmjs.com/package/react-native-safe-area-context#usesafeareainsets

import { useSafeAreaInsets } from 'react-native-safe-area-context';

function Screen() {
  const insets = useSafeAreaInsets();
  
  console.log(insets);
  //{"bottom": 34, "left": 0, "right": 0, "top": 48}

  return <View />;
}
like image 74
Dinçer Canpunar Avatar answered Sep 16 '22 17:09

Dinçer Canpunar


As @mohammed-ashfaq said, react-native-safe-area solves the problem. However, it returns the insets with a promise and I needed those values statically.

Given that, I created react-native-static-safe-area-insets that enables access to the insets values as constants.

like image 30
jphorta Avatar answered Sep 18 '22 17:09

jphorta