Scroll to the Top or Bottom of the ListView in React Native

Scroll to the Top or Bottom of the ListView

Here is an example to Scroll to the Top or Bottom of the ListView in React Native on the Click of Button. We have often seen this type of thing on websites where you scroll towards the button and suddenly a button pop up to take you at the top of the page. It provides a very good user experience. So here is the same example with the React Native FlatList.

In this example, We will  make two buttons

1. To take you to the top of the ListView by using :

listViewRef.scrollTo({ x: 0, y: 0, animated: true });

2. To take you to the Bottom of the ListView by using :

listViewRef.scrollToEnd({ animated: true });

We are using a simple React Native FlatList for this example. So let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Code

Open App.js in any code editor and replace the code with the following code

App.js

// Scroll to the Top or Bottom of the ListView in React Native
// https://aboutreact.com/react-native-scroll-up-or-down-the-listview-on-the-click-of-button/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  View,
  FlatList,
  Text,
  TouchableOpacity,
  Image,
} from 'react-native';

const App = () => {
  let listViewRef;
  const [dataSource, setDataSource] = useState([
    {id: 1, title: 'Button'},
    {id: 2, title: 'Card'},
    {id: 3, title: 'Input'},
    {id: 4, title: 'Avatar'},
    {id: 5, title: 'CheckBox'},
    {id: 6, title: 'Header'},
    {id: 7, title: 'Icon'},
    {id: 8, title: 'Lists'},
    {id: 9, title: 'Rating'},
    {id: 10, title: 'Pricing'},
    {id: 11, title: 'Avatar'},
    {id: 12, title: 'CheckBox'},
    {id: 13, title: 'Header'},
    {id: 14, title: 'Icon'},
    {id: 15, title: 'Lists'},
    {id: 16, title: 'Rating'},
    {id: 17, title: 'Pricing'},
  ]);

  const ItemView = ({item}) => {
    return (
      // Flat List Item
      <Text
        style={styles.itemStyle}
        onPress={() => getItem(item)}>
        {item.id}
        {'.'}
        {item.title.toUpperCase()}
      </Text>
    );
  };

  const ItemSeparatorView = () => {
    return (
      // Flat List Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = (item) => {
    // Function for click on an item
    alert('Id : ' + item.id + ' Title : ' + item.title);
  };

  const upButtonHandler = () => {
    //OnCLick of Up button we scrolled the list to top
    listViewRef.scrollToOffset({
      offset: 0,
      animated: true
    });
  };

  const downButtonHandler = () => {
    //OnCLick of down button we scrolled the list to bottom
    listViewRef.scrollToEnd({animated: true});
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <FlatList
        data={dataSource}
        keyExtractor={(item, index) => index.toString()}
        ItemSeparatorComponent={ItemSeparatorView}
        renderItem={ItemView}
        ref={(ref) => {
          listViewRef = ref;
        }}
      />
      <TouchableOpacity
        activeOpacity={0.5}
        onPress={downButtonHandler}
        style={styles.downButtonStyle}>
        <Image
          source={{
            uri:
              'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_down.png',
          }}
          style={styles.downButtonImageStyle}
        />
      </TouchableOpacity>
      <TouchableOpacity
        activeOpacity={0.5}
        onPress={upButtonHandler}
        style={styles.upButtonStyle}>
        <Image
          source={{
            uri:
              'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_up.png',
          }}
          style={styles.upButtonImageStyle}
        />
      </TouchableOpacity>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  itemStyle: {
    padding: 30,
    fontSize: 20,
  },
  upButtonStyle: {
    position: 'absolute',
    width: 50,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    right: 30,
    bottom: 70,
  },
  upButtonImageStyle: {
    resizeMode: 'contain',
    width: 30,
    height: 30,
  },
  downButtonStyle: {
    position: 'absolute',
    width: 50,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    right: 30,
    top: 70,
  },
  downButtonImageStyle: {
    resizeMode: 'contain',
    width: 30,
    height: 30,
  },
});

export default App;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Download Source Code

Output Screenshots

Output in Online Emulator

This is how you can Scroll to the Top or Bottom of the ListView in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

1 thought on “Scroll to the Top or Bottom of the ListView in React Native”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.