React-Native Detect Screen Notch
Not Using Expo
If you are using React Native without Expo, or an Expo app which has been ejected, you can use the react-native-device-info
package. It has a hasNotch()
function which works pretty well at detecting such devices.
The Native Base Content
, Footer
and Header
components inspect an isIphoneX
theme variable to determine whether or not to add spacing for a device notch.
You can customized your Native Base theme and modify your variables files to use react-native-device-info
to detect the notch:
# native-base-theme/variables/*.js
import DeviceInfo from 'react-native-device-info';
...
isIphoneX = DeviceInfo.hasNotch();
...
Now your Native Base Header
, Footer
and Content
components should add the appropriate spacing for devices that have notches.
Using Expo
Since react-native-device-info
does not work on Expo projects, there is not a simple way to do this. You will have to write a function to accomplish your goal. If you inspect the hasNotch()
source code, you will notice that the function simply does an array lookup based on the device's brand
and model
. You can get the device model using Expo Constants, but they do not make it easy:
import { Platform } from 'react-native;
import Constants from 'expo-constants';
const getDeviceModel = () => Platform.select({
ios: Constants.platform.ios.model,
android: Constants.deviceName
});
However, there is no way to get the device brand
in Expo. Obviously, all ios
devices have a brand of Apple
, but the Android device brands are more elusive. You may be able to construct a lookup array that only uses the device model
, but it may not be as accurate.
I wish there were a better solution for Expo users.
I'm using the approach from this answer https://stackoverflow.com/a/53593067/923497 and it is working fine for me.
In React Native looks like
import { StatusBar, Platform } from 'react-native';
if (Platform.OS === 'android') {
const hasNotch = StatusBar.currentHeight > 24;
}
Since the problem is on android, maybe you should try looking into StatusBar.currentHeight. Since the notch generally is part of the status bar, adding a padding on top of the header the size of the status bar should probably do it.
Safe Area View is the way go to.
The purpose of SafeAreaView is to render content within the safe area boundaries of a device. It is currently only applicable to iOS devices with iOS version 11 or later.
https://reactnative.dev/docs/safeareaview