I'm trying to make an element stay at the top of the screen at all times, vene when scrolling. I found out that position: 'sticky'
does this for regular html. I was wondering if there was something I could add to my css to make the element stick to one place while scrolling using react-native.
I'm trying to make an element stay at the top of the screen at all times, vene when scrolling. I found out that position: 'sticky'
does this for regular html. I was wondering if there was something I could add to my css to make the element stick to one place while scrolling using react-native.
2 Answers
Reset to default 5On ScrollView
there is a prop called stickyHeaderIndices. Pass the index of the ponent that you want to be sticky in this prop. For example, if you want to sticky the header to be sticky from the below code, you have to just pass 1 in stickyHeaderIndices
props like this :
import React from 'react';
import { View, ScrollView, StyleSheet, Text } from 'react-native';
const App = () => {
return (
<ScrollView stickyHeaderIndices={[1]}>
<View>
<Text style={styles.overline}>
Overline
</Text>
</View>
<View>
<Text style={styles.header}>
Header
</Text>
</View>
{/* Your others ponent goes here */}
</ScrollView>
)
}
const styles = StyleSheet.create({
overline: {
fontSize: 12,
fontWeight: '100'
},
header: {
fontSize: 24,
fontWeight: 'bold'
},
spacer: {
height: 10,
}
});
export default App;
This prop accepts the array, so you can also set multiple sticky ponents by passing the index of those all ponents.
I found that ScrollView
's stickyHeaderIndices
didn't work for my use-case, where I had an element that wasn't full-screen. (It stretched the element out to full screen; when I tried to wrap it in a View
, it stopped being sticky.)
What worked for me was simply putting the element I wished to be sticky before the ScrollView
, rather than inside it, and applying absolute positioning. A similar approach also worked for me for a sticky footer.
<MyComponent style={{position: absolute;}}/> // will be sticky to top
<ScrollView>
// scrolling ponents
</ScrollView>
<OtherComponent /> // functionally sticky to bottom; looks like content is scrolling behind it, even though the scrollview just stops before it.