The FlatList
Component is among the simplest and most-used React Native components. If you are just starting out with React Native, you must get a gist of the FlatList
Component and understand its purpose.
While building apps, you will come across some lists; these can be a list of contacts, users, activities, etc. They may seem very easy to implement. But, displaying large data sets or a long list is not that performant. That’s where React Native’s FlatList
component comes into the picture.
flatList
componentThe FlatList
component is used to display large quantities of scrollable list items. Under the hood, the FlatList
component makes use of the ScrollView
component.
Still, it adds a performance factor to it, like only rendering the items visible on the screen, and only updating the items that have been changed. The FlatList
component works great for large items of data that might change over time.
There are two main and required props you need to know about for using FlatList
component – data
and renderItem
.
The data
prop is an array of data that is used as the source for creating the list. The renderItem
is a callback function that will accept the individual item from the data
prop and render a component for it. You no longer need to format the data — instead, you can pass an array and start rendering right away.
Consider that you have a data array with a list of countries in it:
js const data = ["Germany", "Australia", "Sri Lanka", "Japan"];
Now, to render the countries, create a component called Country
:
jsx import { Text, View } from "react-native"; const Country = ({ name }) => ( <View> <Text>{name}</Text> </View> );
Inside the App
component, get the data into the state:
jsx const data = ["Germany", "Australia", "Sri Lanka", "Japan"]; const App = () => { constructor(props) { super(props); this.state = { countries: data } } render() { // ... } }
Next, import the FlatList
component from react-native
and use it to display the countries:
jsx import { FlatList, Text, View } from "react-native"; // ... const App = () => { constructor(props) { super(props); this.state = { countries: data } } render() { return ( <View style={{ flex: 1 }}> <FlatList data={this.state.data} renderItem={({item}) => <Country name={item} />} /> </View> ); } }
The renderItem
function is passed as a single argument, which is an object.
The data you require is in the item
property, so you can use destructuring to access the data. In this case, you need to pass the item
to the name
prop of the Country
component.
Note that this might be different for various cases depending on the props your component might take and the prop types.
Below, you can find the entire code for this section:
jsx import React from "react"; import { FlatList, Text, View } from "react-native"; const data = ["Germany", "Australia", "Sri Lanka", "Japan"]; const Country = ({ name }) => ( <View> <Text>{name}</Text> </View> ); const App = () => { constructor(props) { super(props); this.state = { countries: data } } render() { return ( <View style={{ flex: 1 }}> <FlatList data={this.state.data} renderItem={({item}) => <Country name={item} />} /> </View> ); } } export default App;
In a more practical scenario, you might want to display the data that is fetched from your backend service. In this section, you will see some real-world examples to get up and running with the FlatList
component.
So, start by creating a new project:
sh npx react-native init FlatListDemo
For styling the components, use the react-native-elements
library:
sh yarn add react-native-elements react-native-vector-icons
Start by adding the header component on the screen:
jsx import { Header } from "react-native-elements"; const AppHeader = () => ( <Header centerComponent={{ text: "USERS", style: { color: "#fff" } }} containerStyle={{ paddingTop: 0, height: 60 }} /> ); const App = () => { return ( <View> <AppHeader /> </View> ); };
Next, use the JSON placeholder API to fetch the user info:
jsx class App extends Component { constructor(props) { super(props); this.state = { users: [], isLoading: false, }; } fetchUsers = async () => { this.setState({ isLoading: true }); try { const res = await fetch(JSON_API_URL); const users = await res.json(); this.setState({ users }); } catch (err) { console.log(err); } this.setState({ isLoading: false }); }; componentDidMount() { this.fetchUsers(); } render() { return ( ( )} keyExtractor={(user) => user.id} ItemSeparatorComponent={() => } /> ); } }
The keyExtractor
prop retrieves the keys for the list item. These unique keys notify the FlatList component to keep track of the items and are important when it comes to efficiency and performance.
You will have to select a unique value for the key. In this case, it is the id
. By default, the keyExtractor
falls back to the index of the item, but you will still see the warning.
The ItemSeperatorComponent
prop lets you add a separator component between the list items. In this case, you are adding the Divider
component.
Pull to refresh is an essential functionality that lets the user refresh the data on the screen when the user pulls the screen towards the bottom and loads new data.
Pull to refresh is vital in any app that has an activity or a data feed, which needs to be refreshed to view new content.
This can happen when a user spends a good amount of time on your app browsing the feed, and new data becomes available at some point in time.
Two props are required to implement Pull to Refresh functionality in a FlatList
component – refreshing
and onRefresh
.
The refreshing
prop tells the FlatList
component to show a RefreshControl
component when new data is being loaded.
It accepts a Boolean
value. The onRefresh
is a callback prop that calls the function when the refreshing
prop is set to true
. This function must be responsible for loading new data and updating the list items in the FlatList
component.
jsx class App extends Component { constructor(props) { super(props); this.state = { users: [], isLoading: false, }; } fetchUsers = async () => { this.setState({ isLoading: true }); try { const res = await fetch(JSON_API_URL); const users = await res.json(); this.setState({ users }); } catch (err) { console.log(err); } this.setState({ isLoading: false }); }; componentDidMount() { this.fetchUsers(); } render() { return ( ( )} keyExtractor={(user) => user.id} refreshing={this.state.isLoading} onRefresh={this.fetchUsers} ItemSeparatorComponent={() => } /> ); } }
Pagination is another important functionality to have in your app when there is a lot of data that needs to be loaded.
In practicality, you can’t load all the data at once — it would make your app really slow and less efficient, resulting in poor performance and poor user experience.
For this example, use the fake user generator API, as it has a pagination option and also includes user avatars.
The basic idea is to have a state variable in your component that keeps track of the current page and increments it when the user reaches the end of the list.
When the user reaches at the end, fetch the new list data with the current page value. This can be implemented in the FlatList
component using the onEndReached
prop. The onEndReached
props accept a function that is triggered when the user reaches at the end of the list.
jsx const Loader = () => ( <View style={{ minHeight: 230, padding: 20 }}> <ActivityIndicator color="#000" size="large" style={{ alignSelf: "center" }} /> </View> ); class App extends Component { constructor(props) { super(props); this.state = { users: [], isLoading: false, isLoadingMore: false, page: 1, }; } fetchUsers = async () => { this.setState({ isLoading: true }); try { const res = await fetch(`${JSON_API_URL}&page=${this.state.page}`); const { results: users } = await res.json(); if (this.state.page === 1) this.setState({ users }); else this.setState({ users: [...this.state.users, ...users] }); } catch (err) { console.log(err); } this.setState({ isLoading: false }); }; refreshUsers = () => { this.setState({ page: 1 }, () => { this.fetchUsers(); }); }; loadMoreUsers = () => { this.setState({ page: this.state.page + 1, isLoadingMore: true }, () => { this.fetchUsers(); this.setState({ isLoadingMore: false }); }); }; componentDidMount() { this.fetchUsers(); } render() { return ( <View> <AppHeader /> <FlatList data={this.state.users} renderItem={({ item }) => ( <ListItem title={`${item.name.first} ${item.name.last}`} subtitle={item.login.username} leftAvatar={{ source: { uri: item.picture.thumbnail } }} /> )} keyExtractor={(user) => user.login.uuid} refreshing={this.state.isLoading} onRefresh={this.refreshUsers} ItemSeparatorComponent={() => <Divider />} ListFooterComponent={this.state.isLoadingMore && <Loader />} onEndReachedThreshold={0.1} onEndReached={this.loadMoreUsers} /> </View> ); } }
That is it for FlatList
component in React Native.
Now that you have learned about the FlatList
component, you can fetch data from any API and display the list items in your app.
Make sure you implement pull to refresh and infinite scroll in your app as it improves the overall user experience and gives your app a more professional finish.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.
One Reply to "How to use the FlatList component in React Native"
should data={this.state.data} in fact be data={this.state.countires} ? as this.state.data is undefined