In this lesson, you will learn how to control the visual "stacking order" of your UI components when they overlap on the screen.
Understanding the Stacking Context
In React Native, layout isn't just about side-by-side positioning; it’s about depth. By default, components are rendered in the order they appear in your JSX. The element defined last in your code sits "on top" of elements defined earlier. However, when you use Absolute Positioning (setting position: 'absolute'), components often overlap. This is where zIndex becomes essential.
The zIndex property determines which component appears closer to the user. A higher integer value brings an element forward, while a lower value pushes it behind.
The Stacking Hierarchy
Think of your screen as a stack of transparent sheets of glass. If you want a "Floating Action Button" to appear above a background image, you assign it a higher zIndex.
const LayeredLayout = () => (
<View style={styles.container}>
{/* This sits at the bottom */}
<View style={styles.backgroundBox} />
{/* This sits on top because of the higher zIndex */}
<View style={styles.floatingButton} />
</View>
);
const styles = StyleSheet.create({
backgroundBox: {
position: 'absolute',
width: 200,
height: 200,
backgroundColor: 'blue',
zIndex: 1,
},
floatingButton: {
position: 'absolute',
width: 50,
height: 50,
backgroundColor: 'red',
zIndex: 2, // Clearly higher than the blue box
},
});
Important Nuances
- Platform Differences: On Android,
zIndexis strictly supported. On iOS,zIndexfollows the hierarchy of the parent views. If a parent container has a lowerzIndexthan a sibling container, the children inside that parent cannot be "pulled" in front of the sibling. - Implicit Stacking: Remember that if two elements have the same
zIndex, the one defined last in your component tree will naturally render on top. Only usezIndexwhen the default source-order behavior isn't providing the depth you need for your design.
Key Takeaway: Use zIndex to explicitly define the depth of overlapping components, keeping in mind that it acts as a secondary override to your code's natural rendering order.