Course contentsShow
← React Native
Lesson 199 of 1,5553. Core Primitive ComponentsFree lesson

Implementing Scroll-to-Top Actions

Learners will create programmatic triggers to return users to the start of long lists.

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

  1. Define the Ref: We initialize listRef using useRef(null). This acts as a "handle" to our FlatList.
  2. Attach the Ref: We pass listRef to the ref prop of the FlatList.
  3. Trigger the Action: Inside our button's onPress, we access listRef.current. We then call scrollToOffset({ offset: 0 }). The offset: 0 coordinate 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.