Sticky Scroll Headers in React Native

December 25, 2020 - 1 min read

Some apps have a special behavior, as you scroll their content. You may call this Sticky Header. This means a list's feature of keeping a specific item sticked to its top, until the next sticky item is scrolled over. The use case in general could be a ScrollView that has specific sections or categories that you want to keep sticky.

Luckily, the ScrollView component from core React Native has this feature already implemented. It is called stickyHeaderIndices and accepts an "array of child indices determining which children get docked to the top of the screen when scrolling".

But first, we want to define the code for the scroll view items. It is a simple wrapped Text component, with larger font size, color and margin.

import { Text } from 'react-native';
const TextEl = ({ children }) => (
<Text
style={{
fontSize: 32,
fontWeight: 'bold',
marginBottom: 24,
backgroundColor: '#fff',
}}>
{children}
</Text>
);
view raw sticky.0.jsx hosted with ❤ by GitHub

Now, we have to define the ScrollView component. You will see that it has the prop stickyHeaderIndices={[0, 3]} which means that the first and fourth element will stick to the top of the list when scrolling.

import { ScrollView } from 'react-native';
const StickyList = () => {
return (
<ScrollView
style={{ flex: 1, backgroundColor: '#fff' }}
stickyHeaderIndices={[0, 3]}>
<TextEl>sticky 0</TextEl>
<TextEl>not sticky</TextEl>
<TextEl>not sticky</TextEl>
<TextEl>sticky 1</TextEl>
<TextEl>not sticky</TextEl>
<TextEl>not sticky</TextEl>
<TextEl>not sticky</TextEl>
<TextEl>not sticky</TextEl>
</ScrollView>
);
};
view raw sticky.1.jsx hosted with ❤ by GitHub

Originally published at https://mariusreimer.com on December 25, 2020.