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 to store the X and Y coordinates of the item.
const [dataSourceCords, setDataSourceCords] = useState([]);
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.
<View
key={key}
style={styles.item}
onLayout={(event) => {
const layout = event.nativeEvent.layout;
dataSourceCords[key] = layout.y;
setDataSourceCords(dataSourceCords);
console.log(dataSourceCords);
console.log('height:', layout.height);
console.log('width:', layout.width);
console.log('x:', layout.x);
console.log('y:', layout.y);
}}>
<Text style={styles.itemStyle} onPress={() => getItem(item)}>
{item.id}. {item.title}
</Text>
<ItemSeparatorView />
</View>
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).
ref.scrollTo({
x: 0,
y: dataSourceCords[scrollToIndex - 1],
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 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
Now Open App.js in any code editor and replace the code with the following code
App.js
// Scroll to a Specific Item in ScrollView List View
// https://aboutreact.com/scroll_to_a_specific_item_in_scrollview_list_view/
// import React in our code
import React, {useState, useEffect} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
View,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
TextInput,
} from 'react-native';
const App = () => {
const [dataSource, setDataSource] = useState([]);
const [scrollToIndex, setScrollToIndex] = useState(0);
const [dataSourceCords, setDataSourceCords] = useState([]);
const [ref, setRef] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
setDataSource(responseJson);
})
.catch((error) => {
console.error(error);
});
}, []);
const scrollHandler = () => {
console.log(dataSourceCords.length, scrollToIndex);
if (dataSourceCords.length > scrollToIndex) {
ref.scrollTo({
x: 0,
y: dataSourceCords[scrollToIndex - 1],
animated: true,
});
} else {
alert('Out of Max Index');
}
};
const ItemView = (item, key) => {
return (
// Flat List Item
<View
key={key}
style={styles.item}
onLayout={(event) => {
const layout = event.nativeEvent.layout;
dataSourceCords[key] = layout.y;
setDataSourceCords(dataSourceCords);
console.log(dataSourceCords);
console.log('height:', layout.height);
console.log('width:', layout.width);
console.log('x:', layout.x);
console.log('y:', layout.y);
}}>
<Text
style={styles.itemStyle}
onPress={() => getItem(item)}>
{item.id}. {item.title}
</Text>
<ItemSeparatorView />
</View>
);
};
const ItemSeparatorView = () => {
return (
// Flat List Item Separator
<View style={styles.itemSeparatorStyle} />
);
};
const getItem = (item) => {
// Function for click on an item
alert('Id : ' + item.id + ' Title : ' + item.title);
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<View style={styles.searchContainer}>
<TextInput
value={
String(
scrollToIndex ?
scrollToIndex : 0
)
}
numericvalue
keyboardType={'numeric'}
onChangeText={(scrollToIndex) => {
setScrollToIndex(
parseInt(
scrollToIndex != '' ?
scrollToIndex : 0
),
);
}}
placeholder={'Enter the index to scroll'}
style={styles.searchInput}
/>
<TouchableOpacity
activeOpacity={0.5}
onPress={scrollHandler}
style={styles.searchButton}>
<Text style={styles.searchButtonText}>
Go to Index
</Text>
</TouchableOpacity>
</View>
{/* List Item as a function */}
<ScrollView
ref={(ref) => {
setRef(ref);
}}>
{dataSource.map(ItemView)}
</ScrollView>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
},
itemStyle: {
padding: 10,
},
itemSeparatorStyle: {
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
},
searchContainer: {
flexDirection: 'row',
backgroundColor: '#1e73be',
padding: 5,
},
searchInput: {
flex: 1,
backgroundColor: 'white',
padding: 10,
},
searchButton: {
padding: 15,
backgroundColor: '#f4801e',
},
searchButtonText: {
color: '#fff',
},
});
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
Output Screenshots
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. 🙂