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.
This post is a solution for the most recent query asked by one of our AboutReact family member Pranjul Mishra. While solving the query I found something interesting so I decided to make a post on it.
Note: We are not going to use any external library to do this. We are going to use 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.
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.
1 2 3 4 5 6 | 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 name scrollview_ref.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <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).
1 2 3 4 5 | 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.
Now Open App.js in any code editor and replace the code with the following code.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | /*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 devicereact-native run-android
or on the iOS Simulator by runningreact-native run-ios
(macOS only).
Android
IOS
This is how you can Scroll to a Specific Item in ScrollView ListView. If you have any doubt 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. 🙂