View in React Native

A deep dive into how to use the View component in React Native and its modifiers such as pointerEvents, onLayout, style, and others.

In this tutorial, we'll take a deep dive into how to use the View component and its modifiers in React Native.

View

View component in React Native serves as a fundamental block for building UI.

It directly corresponds to UIView when running on iOS devices and android.view when running on Android.

<View>
  ...
</View>

Nested Views

You can have any number of children nested inside View. This is useful for structuring your UI hierarchy.

<View>
  <View style={{backgroundColor: 'blue', width: 100, height: 100}} />
  <View style={{backgroundColor: 'red', width: 100, height: 100}} />
</View>

Dynamic Views

For Dynamic Views (or basically any other components) you can use JavaScript’s conditional statements within your JSX.

export default function Example() {
  const shouldRenderRedBox = false;

  return (
    <View>
      <View style={{backgroundColor: 'blue', width: 100, height: 100}} />

      {shouldRenderRedBox && (
        <View style={{backgroundColor: 'red', width: 100, height: 100}} />
      )}
    </View>
  )
}

Calculating View Dimensions and Position on the screen

View component has an onLayout property that is used to determine component’s position on the screen and its dimensions.

onLayout is fired immediately after mounting with a callback event containing x, y, width, and height properties.

<View onLayout={({ nativeEvent: { layout } }) => {
  console.log(`Position on the screen: ${layout.x} x ${layout.y}`)
  console.log(`View dimensions: ${layout.width} x ${layout.height}`)
}}>
  ...
</View>

Disabling Touch Events

In certain scenarios, you may want to prevent touch events from happening on a View component. The pointerEvents property allows you to control whether a View can respond to touch events.

By setting this property to none, you can disable all touch interactions on the component.

<View pointerEvents="none">
  ...
</View>

We hope you enjoyed this content and now better understand how to use View in React Native.

Never miss a beat

Stay in the loop with our latest updates and offers - no spam, just the good stuff!