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 :

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

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

this.ListView_Ref.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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

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

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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

//This is an example code to Scroll Up or Down ListView on Button Click//
import React, { Component } from 'react';
//import react in our code.

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

export default class Mynewproject extends Component {
  constructor(props) {
    super(props);
    //Preparing the data for the ListView
    this.state = {
      dataSource: [
        'Chinkara',
        'MotorsForce',
        'MotorsIPMLHindustan',
        'Mahindra',
        'Reva',
        'Electric',
        'VehiclesMaruti',
        'Suzuki',
        'IndiaOpel',
        'IndiaPremier',
        'LtdSan',
        'StormSML',
        'IsuzuStandardTara',
        'InternationalTata',
        'Motor',
        'Chinkara',
        'MotorsForce',
        'MotorsIPMLHindustan',
        'Mahindra',
        'Reva',
        'Electric',
        'VehiclesMaruti',
        'Suzuki',
        'IndiaOpel',
        'IndiaPremier',
        'LtdSan',
        'StormSML',
        'IsuzuStandardTara',
        'InternationalTata',
        'Motor',
      ]
    };
  }

  ListViewItemSeparator = () => {
    return (
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#000',
        }}
      />
    );
  };

  GetListViewItem(rowData) {
    Alert.alert(rowData);
  }

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

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

  render() {
    return (
      <View style={styles.MainContainer}>
        <FlatList
          data={this.state.dataSource}
          keyExtractor={(item, index) => index.toString()}
          ItemSeparatorComponent={this.ListViewItemSeparator}
          ref={(ref) => {
            this.ListView_Ref = ref;
          }}
          renderItem={({ item }) => (
            <Text
              style={styles.rowViewContainer}
              onPress={this.GetListViewItem.bind(this, item)}>
              {item}
            </Text>
          )}
        />
        <TouchableOpacity
          activeOpacity={0.5}
          onPress={this.downButtonHandler}
          style={styles.downButton}>
          <Image
            source={{
              uri:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_down.png',
            }}
            style={styles.downButtonImage}

          />
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.5}
          onPress={this.upButtonHandler}
          style={styles.upButton}>
          <Image
            source={{
              uri:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_up.png',
            }}
            style={styles.upButtonImage}
          />
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    justifyContent: 'center',
    flex: 1,
    margin: 10,
    paddingTop: 40,
  },
  rowViewContainer: {
    fontSize: 18,
    paddingRight: 10,
    paddingTop: 10,
    paddingBottom: 10,
  },
  upButton: {
    position: 'absolute',
    width: 50,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    right: 30,
    bottom: 70,
  },
  upButtonImage: {
    resizeMode: 'contain',
    width: 30,
    height: 30,
  },
  downButton: {
    position: 'absolute',
    width: 50,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    right: 30,
    top: 70,
  },
  downButtonImage: {
    resizeMode: 'contain',
    width: 30,
    height: 30,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

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. 🙂


Related Posts

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.