In this lesson, you will learn how to programmatically jump to the start of a long list when a user performs an action, such as tapping a button.
Why Scroll-to-Top?
When users are deep into a long list (like a feed or a large data table), scrolling back up manually can be tedious. By providing a "Scroll-to-Top" button, you improve user experience by offering a quick "reset" trigger. Since you have already mastered Managing List Scroll Positions, you know that FlatList components keep track of their own scroll state. To manipulate this from outside the list, we use a ref.
The Mechanism: Using useRef
To control the scroll position, we create a ref and attach it to the FlatList. This gives us a direct reference to the list's methods, specifically scrollToOffset.
import React, { useRef } from 'react';
import { FlatList, Button, View } from 'react-native';
const ScrollToTopList = () => {
const listRef = useRef(null);
const handleScrollToTop = () => {
// animated: true makes the scroll smooth
listRef.current?.scrollToOffset({ offset: 0, animated: true });
};
return (
<View>
<Button title="Back to Top" onPress={handleScrollToTop} />
<FlatList
ref={listRef}
data={largeDataSet}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
</View>
);
};
How It Works
- Define the Ref: We initialize
listRefusinguseRef(null). This acts as a "handle" to ourFlatList. - Attach the Ref: We pass
listRefto therefprop of theFlatList. - Trigger the Action: Inside our button's
onPress, we accesslistRef.current. We then callscrollToOffset({ offset: 0 }). Theoffset: 0coordinate represents the very beginning of the list container.
Setting animated: true is recommended, as it provides visual context to the user that they are returning to the start, rather than instantly "teleporting" them, which can be jarring. You can place this button in a sticky header or at the bottom of the screen to keep it accessible as the user explores your list content.
Key Takeaway: By attaching a ref to your FlatList, you gain direct control to trigger a smooth, programmatic scroll back to the zero-offset position at any time.