How to modify the padding in SafeAreaView?

Michal picture Michal · Aug 29, 2019 · Viewed 7.9k times · Source

I am trying to position element in the left-upper corner of the screen (there is some margin around). Because of the notch on the iPhone X I am using SafeAreaView. Unfortunately the SafeAreaView padding is enormous, it goes way out of the status bar / notch area. Because of that the element which should visually be in the corner it's now much lower than on other devices.

I looked into StatusBar.currentHeight, but that is supported only for Android. Another option was to use https://github.com/react-native-community/react-native-safe-area-view which has a forceInset parameter. Unfortunately, setting it as { top: xx } makes it work like a normal View with a top padding for all devices (the ones without notch as well).

How can I have a SafeAreaView but with a modified top padding?

Answer

vitosorriso picture vitosorriso · Aug 29, 2019

I had a similar problem months ago, so I wrote an util to give me the correct height of top/bottom SafeArea to add as padding to a normal react-native View, and then play with them by adding/removing more padding. Here is the code:

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

export function isIphoneX () {
  const iphoneXLength = 812
  const iphoneXSMaxLength = 896
  const windowDimensions = Dimensions.get('window')
  return (
    Platform.OS === 'ios' &&
    !Platform.isPad &&
    !Platform.isTVOS &&
    (windowDimensions.width === iphoneXLength ||
      windowDimensions.height === iphoneXLength ||
      windowDimensions.width === iphoneXSMaxLength ||
      windowDimensions.height === iphoneXSMaxLength)
  )
}

const DimensionsStyle = {
  safeAreaTopHeight: Platform.OS === 'ios' ? (isIphoneX() ? 44 : 20) : 0,
  safeAreaBottomHeight: Platform.OS === 'ios' && isIphoneX() ? 35 : 0,
  tabBarHeight: Platform.OS === 'ios' ? 17 : 20,
  bottomAreaHeight: Platform.OS === 'ios' && isIphoneX() ? 34 : 0
}

export default DimensionsStyle

This code works because we know that iPhone X and iPhone XS have a 812p height, and iPhone XSMax and XR have 896p height.

Then you can simply import this util into your view and use it like this:

import Dimension from '../../../utils/DimensionUtils' // path of the util
//
// rest of the code
//
const styles = StyleSheet.create({
  container: {
    paddingTop: Dimension.safeAreaTopHeight // here you can edit the height of the safeare :))
  }
})