There have been quite a few ways to create a scrolling list in React Native, and most notably, they have been the ScrollView and the FlatList.
React Native FlatList
React Native FlatList is a built-in component to make an efficient scrolling list of data. There are two primary props you need to know in the FlatList: data and renderItem.
The first is an array of data used to create the list, typically an array of objects. The second function will take an individual data array element and render a component.
The FlatList component is an easy way to make an efficient scrolling list of data. Not only is it practical, but it’s got a straightforward API to work with.
If you’ve used or are familiar with the ListView component, it’s very similar, just better in (almost) every way. ? No longer do you have to format the data — you can pass it an array of data to get to rendering right away.
The FlatList offers the following handy features.
React Native FlatList Features
- Fully cross-platform.
- Optional horizontal mode.
- Configurable viewability callbacks.
- Header support.
- Footer support.
- Separator support.
- Pull to Refresh.
- Scroll loading.
- ScrollToIndex support.
We will start this tutorial by installing React Native On Mac using the react-native-cli.
Step 1: Install React Native On Mac
Go to the terminal and hit the following command.
react-native init FlatListApp
It will install the dependencies and give some boilerplate. Go into the project directory.
cd FlatListApp
Now, start the package manager and the simulator with the following command. I am using iPhone X as a Simulator.
react-native run-ios --simulator="iPhone X"
It will take 2-3 minutes to compile the first time, and then you can see it on your iPhone X screen like the below image.
Step 2: Create the sample data and server.
We need the fake data to work with the React Native FlatList Example; that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using the Yarn package manager.
yarn add json-server
Okay, now we need to create one folder called data inside the root folder, and in that folder, create one file called db.json. Let us add the following data in the db.json file for testing purposes.
{ "users": [ { "name": "Proxima Midnight", "email": "proxima@appdividend.com" }, { "name": "Ebony Maw", "email": "ebony@appdividend.com" }, { "name": "Black Dwarf", "email": "dwarf@appdividend.com" }, { "name": "Mad Titan", "email": "thanos@appdividend.com" }, { "name": "Supergiant", "email": "supergiant@appdividend.com" }, { "name": "Loki", "email": "loki@appdividend.com" }, { "name": "corvus", "email": "corvus@appdividend.com" }, { "name": "Proxima Midnight", "email": "proxima1@appdividend.com" }, { "name": "Ebony Maw", "email": "ebony1@appdividend.com" }, { "name": "Black Dwarf", "email": "dwarf1@appdividend.com" }, { "name": "Mad Titan", "email": "thanos1@appdividend.com" }, { "name": "Supergiant", "email": "supergiant1@appdividend.com" }, { "name": "Loki", "email": "loki1@appdividend.com" }, { "name": "corvus", "email": "corvus1@appdividend.com" } ] }
Okay, now this is the file. The json-server will serve when we hit the network request. So type the following command to start the json-server.
Switch to the browser and go to this URL: http://localhost:5200/users
Step 3: Create a service that fetches the data from the server.
In the root folder, create one folder called to service; in that folder, create one file called FetchData.js.
// FetchData.js const URI = 'http://localhost:5200'; export default { async fetchUsers() { try { let response = await fetch(URI + '/users'); let responseJsonData = await response.json(); return responseJsonData; } catch(e) { console.log(e) } } }
Fetch is the network library provided by React Native. It is a promise-based library, so we must wait to resolve it. Here we have used async/await.
Step 4: Modify the App.js file to display the users’ data.
We will display the users’ data in FlatList.
// App.js import React, { Component } from 'react'; import { StyleSheet, Text, View, FlatList } from 'react-native'; import ajax from './service/FetchData'; export default class App extends Component { state = { users: [] } async componentDidMount() { const users = await ajax.fetchUsers(); this.setState({users}); } render() { return ( <View style={styles.container} > <Text style={styles.h2text}> Black Order </Text> <FlatList data={this.state.users} showsVerticalScrollIndicator={false} renderItem={({item}) => <View style={styles.flatview}> <Text style={styles.name}>{item.name}</Text> <Text style={styles.email}>{item.email}</Text> </View> } keyExtractor={item => item.email} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, marginTop: 50, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, h2text: { marginTop: 10, fontFamily: 'Helvetica', fontSize: 36, fontWeight: 'bold', }, flatview: { justifyContent: 'center', paddingTop: 30, borderRadius: 2, }, name: { fontFamily: 'Verdana', fontSize: 18 }, email: { color: 'red' } });
With that completed, you can go ahead and start rendering the data. To do so, you first want to import { StyleSheet, Text, View, FlatList } from {react-native,“; so you have the necessary components to render the data.
The remainder of the work will take place in the render method. But, first, we fetched the data from the server and then set the user’s state.
FlatList consumes that users’ data via this.state.users.
Then you want to render the content with the renderItem prop. Again, the function passes a single argument, an object.
The data you’re interested in is on the item key, so you can use destructuring to access that from within the function. Then return a component utilizing that data.
If you find any warning that the list elements are missing keys, these unique keys allow the VirtualizedList (which is what FlatList is built on) to track items and aid in the efficiency of the list. I won’t dive into it, but I know it’s essential.
To alleviate this issue, you want to choose a piece of data unique to each item. In this case, you can use the user’s email address because that will be unique to each item.
You can then use the keyExtractor prop to specify which piece of data should be used as the key.
So, we have defined the unique key from our data.
I have hidden the verticle scrollbar using the property showsVerticalScrollIndicator={false}. So our final output looks like this.
That is it.
Hi, man. The list from db.json just dont appears. Can you help me? The code is ‘copy & paste’ from here. Thanks
it is possible to fetch json data without listview or flatlist?
like in simple view or swipeview?
To make it work in Android Emulator, the address of the development machine is 10.0.2.2 not localhost. Replace “const URI = ‘http://localhost:5200’;” with “const URI = ‘http://10.0.2.2:5200’;” in FetchData.js
Read more on StackOverflow: https://stackoverflow.com/questions/9808560/why-do-we-use-10-0-2-2-to-connect-to-local-web-server-instead-of-using-computer
thanks you very much :D. Your comment makes my life easier.
How to make scrollToTop in Flatlist?
Hi, man. The list from db.json just dont appears. Can you help me? The code is ‘copy & paste’ from here.