Skip to content

Instantly share code, notes, and snippets.

@tiagotedsky
Created April 29, 2021 12:30
Show Gist options
  • Save tiagotedsky/076887546530a509ee602318f92ca7ac to your computer and use it in GitHub Desktop.
Save tiagotedsky/076887546530a509ee602318f92ca7ac to your computer and use it in GitHub Desktop.
StackOverflow - React native - scroll to location
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