-
-
Save tiagotedsky/076887546530a509ee602318f92ca7ac to your computer and use it in GitHub Desktop.
StackOverflow - React native - scroll to location
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useRef, useState} from 'react'; | |
import { | |
StyleSheet, | |
Text, | |
View, | |
SafeAreaView, | |
SectionList, | |
StatusBar, | |
Button, | |
} from 'react-native'; | |
const DATA = [ | |
{ | |
title: 'Main dishes', | |
data: ['Pizza', 'Burger', 'Risotto'], | |
}, | |
{ | |
title: 'Sides', | |
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'], | |
}, | |
{ | |
title: 'Drinks', | |
data: ['Water', 'Coke', 'Beer'], | |
}, | |
{ | |
title: 'Desserts', | |
data: ['Cheese Cake', 'Ice Cream'], | |
}, | |
]; | |
const Item = ({title}) => ( | |
<View style={styles.item}> | |
<Text style={styles.title}>{title}</Text> | |
</View> | |
); | |
const App = () => { | |
const sectionListRef = useRef(null); | |
return ( | |
<SafeAreaView style={styles.container}> | |
<Button | |
title="Scroll" | |
onPress={() => { | |
sectionListRef.current.scrollToLocation({ | |
itemIndex: 6, | |
}); | |
}} | |
/> | |
<SectionList | |
ref={sectionListRef} | |
onMomentumScrollEnd={() => alert('ends')} | |
sections={DATA} | |
keyExtractor={(item, index) => item + index} | |
renderItem={({item}) => <Item title={item} />} | |
renderSectionHeader={({section: {title}}) => ( | |
<Text style={styles.header}>{title}</Text> | |
)} | |
/> | |
</SafeAreaView> | |
); | |
}; | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
paddingTop: StatusBar.currentHeight, | |
marginHorizontal: 16, | |
}, | |
item: { | |
backgroundColor: '#f9c2ff', | |
padding: 20, | |
marginVertical: 8, | |
}, | |
header: { | |
fontSize: 32, | |
backgroundColor: '#fff', | |
}, | |
title: { | |
fontSize: 24, | |
}, | |
}); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment