In this lesson, you will learn how to anchor UI elements to the top of a screen as a user scrolls through content using the stickyHeaderIndices property.
The Problem: Content Obsolescence
When building long-form content screens, your navigational UI—like category tabs or section titles—often scrolls away as the user moves down the page. This forces the user to scroll back up to navigate elsewhere. A "Sticky Header" solves this by keeping vital controls pinned at the top of the viewport once they hit the edge.
The Solution: stickyHeaderIndices
In React Native, the ScrollView component makes this incredibly easy through the stickyHeaderIndices prop. This prop accepts an array of numbers representing the index of the child elements you want to "stick."
If you have a ScrollView containing a list of components, React Native tracks them based on their order. If you want the first element to stick, you simply pass [0].
<ScrollView stickyHeaderIndices={[0]}>
<View style={styles.header}>
<Text>I stay pinned to the top!</Text>
</View>
<View style={styles.content}>
{/* Lots of scrollable content here */}
</View>
</ScrollView>
How it Works
When the ScrollView detects that an element at a specified index has reached the top boundary of the container, it transitions that component from a standard relative layout position to an absolute position relative to the ScrollView’s parent. As the user continues to scroll, the component stays locked in place until the next sticky element (if provided) pushes it out of the way.
It is important to remember that this only works for direct children of the ScrollView. If you wrap your header in another container that isn't a direct child, the indexing will shift, and the sticking effect will fail. Always ensure your header is a top-level child of the ScrollView to maintain consistent layout behavior.
Key Takeaway: Use the stickyHeaderIndices prop on a ScrollView to pin specific direct children to the top of the screen automatically as the user scrolls.