In this lesson, you will learn how to control which elements appear on top or behind others when they occupy the same space on your screen.
The Concept of Stacking
When you place components in a layout, they naturally stack based on the order they appear in your code. Imagine laying sheets of paper on a desk; the last piece of paper you place down sits on top of all the previous ones. In React Native, the View component that is defined last in your JSX will render "on top" of the ones defined before it.
However, sometimes you need to manually override this natural order—for example, if you want a floating notification button to hover above a list of items. This is where zIndex comes in.
Using zIndex
The zIndex property is a style prop that accepts an integer. A higher integer brings the component closer to the user (the foreground), while a lower integer pushes it further back (the background).
Look at this simple example:
<View style={{ position: 'absolute' }}>
{/* This box is at the bottom of the stack */}
<View style={{ zIndex: 1, backgroundColor: 'blue', width: 100, height: 100 }} />
{/* This box will cover the blue one because of the higher zIndex */}
<View style={{ zIndex: 2, backgroundColor: 'red', width: 100, height: 100, marginTop: -50 }} />
</View>
Important Rule: The Stacking Context
It is important to remember that zIndex works within its own parent container. If you have two different parent View containers, the zIndex of a child element inside one cannot "jump" over the other parent container's layer. You are effectively managing the "depth" of siblings relative to each other within the same wrapping component. If your elements aren't overlapping as expected, ensure they share the same parent and that their parent hasn't constrained their ability to stack.
Key Takeaway: The zIndex property allows you to explicitly define the visual stacking order of sibling components, where a higher value brings an element to the front.