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 style={{ flex: 1 }}>
<View style={{ backgroundColor: "#ff006e", flex: 1 }} />
<View style={{ backgroundColor: "#fb5607", flex: 2 }} />
<View style={{ backgroundColor: "#ffbe0b", flex: 3 }} />
</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>