Scroll to a Specific Item in ScrollView List View

Scroll to a Specific Item in ScrollView ListView

In this example, we will see how to Scroll to a Specific Item in ScrollView ListView. If you are not clear with the topic then you can imagine you have made a list using scroll view something like the example of Making a List using ScrollView and now you want to scroll to a specific item in the ScrollView list. For example, you are searching any data from the ScrollView List array and found the matching data on index 7 in the array now you want to scroll the list to item 7, In this situation, you can take the help from this example.

Note: We are not going to use any external library to do this. We are going to use the onLayout prop of the View component provided by React Native.

In this example, we will create a List using Scroll View to hold the data, a TextInput and a button to take the index as input and scroll to the item.

How to Scroll to the Specific item?

1. To scroll to the specific item first we will make a blank array in the constructor to store the X and Y coordinates of the item.

constructor() {
    super();
    //Blank array to store the location of each item
    this.arr = [];
    this.state = { dynamicIndex: 0 };
}

2. While rendering the item we will store the X and Y location of the item in the array. These locations can be found using the onLayout prop of the view Component. We have also added a reference to the ScrollView with the name scrollview_ref.

<ScrollView
  ref={ref => {
    this.scrollview_ref = ref;
  }}>
  {/*Loop of JS which is like foreach loop*/}
  {this.items.map((item, key) => (
    //key is the index of the array
    //item is the single item of the array
    <View
      key={key}
      style={styles.item}
      onLayout={event => {
        const layout = event.nativeEvent.layout;
        this.arr[key] = layout.y;
        console.log('height:', layout.height);
        console.log('width:', layout.width);
        console.log('x:', layout.x);
        console.log('y:', layout.y);
      }}>
      <Text style={styles.text}>
        {key}. {item}
      </Text>
      <View style={styles.separator} />
    </View>
  ))}
</ScrollView>

3. After the 2nd step, you have a ScrollView list with the data listed from the array and an array with the name arr which holds the X and Y location of the item on the same index as the data array has. Now, whenever we want to scroll to a specific location we can use scrollTo which is a property of ScrollView. In this, we have to pass the X and Y location to scroll and animated (True/False).

this.scrollview_ref.scrollTo({
    x: 0,
    y: this.arr[this.state.dynamicIndex],
    animated: true,
});

That is it. 🙂

Now you can see the full example code below.

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

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

App.js

/*Example to Scroll to a specific position in scrollview*/
import React, { Component } from 'react';
//import react in our project

import {
  View,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  Image,
  TextInput,
} from 'react-native';
//import all the components we needed

export default class App extends Component {
  constructor() {
    super();
    //Array of Item to add in Scrollview
    this.items = [
      'zero',
      'one',
      'two',
      'three',
      'four',
      'five',
      'six',
      'seven',
      'eight',
      'nine',
      'ten ',
      'eleven',
      'twelve',
      'thirteen',
      'fourteen',
      'fifteen',
      'sixteen',
      'seventeen',
      'eighteen',
      'nineteen',
      'twenty ',
      'twenty-one',
      'twenty-two',
      'twenty-three',
      'twenty-four',
      'twenty-five',
      'twenty-six',
      'twenty-seven',
      'twenty-eight',
      'twenty-nine',
      'thirty',
      'thirty-one',
      'thirty-two',
      'thirty-three',
      'thirty-four',
      'thirty-five',
      'thirty-six',
      'thirty-seven',
      'thirty-eight',
      'thirty-nine',
      'forty',
    ];
    //Blank array to store the location of each item
    this.arr = [];
    this.state = { dynamicIndex: 0 };
  }
  downButtonHandler = () => {
    if (this.arr.length >= this.state.dynamicIndex) {
      // To Scroll to the index 5 element
      this.scrollview_ref.scrollTo({
        x: 0,
        y: this.arr[this.state.dynamicIndex],
        animated: true,
      });
    } else {
      alert('Out of Max Index');
    }
  };
  render() {
    return (
      <View style={styles.container}>
        <View
          style={{
            flexDirection: 'row',
            backgroundColor: '#1e73be',
            padding: 5,
          }}>
          <TextInput
            value={String(this.state.dynamicIndex)}
            numericvalue
            keyboardType={'numeric'}
            onChangeText={dynamicIndex => this.setState({ dynamicIndex })}
            placeholder={'Enter the index to scroll'}
            style={{ flex: 1, backgroundColor: 'white', padding: 10 }}
          />
          <TouchableOpacity
            activeOpacity={0.5}
            onPress={this.downButtonHandler}
            style={{ padding: 15, backgroundColor: '#f4801e' }}>
            <Text style={{ color: '#fff' }}>Go to Index</Text>
          </TouchableOpacity>
        </View>
        <ScrollView
          ref={ref => {
            this.scrollview_ref = ref;
          }}>
          {/*Loop of JS which is like foreach loop*/}
          {this.items.map((item, key) => (
            //key is the index of the array
            //item is the single item of the array
            <View
              key={key}
              style={styles.item}
              onLayout={event => {
                const layout = event.nativeEvent.layout;
                this.arr[key] = layout.y;
                console.log('height:', layout.height);
                console.log('width:', layout.width);
                console.log('x:', layout.x);
                console.log('y:', layout.y);
              }}>
              <Text style={styles.text}>
                {key}. {item}
              </Text>
              <View style={styles.separator} />
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 30,
  },
  separator: {
    height: 1,
    backgroundColor: '#707080',
    width: '100%',
  },

  text: {
    fontSize: 16,
    color: '#606070',
    padding: 10,
  },
});

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

Android

      
   

IOS

         

      

Output in Online Emulator

This is how you can Scroll to a Specific Item in ScrollView ListView. 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. 🙂

Leave a Comment

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