React FlatList : How to use this component

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 Flatlist component comes into the picture.

An introduction to React Flatlist component

flatlist

The React Flatlist component is used to display large quantities of scrollable list items. To clarify, the React 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 React 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 React Flatlist component – data and renderItem.

Firstly, data prop is an array of data that is used as the source for creating the list. And, 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.

Basic Usage

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 React 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;

Fetching data from an API

In a more practical scenario, you might want to display the data that is fetched from your backend service. To clarify, you will see some real-world examples to get up and running with the React 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>
);
};

Then, 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. To calrify, 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

Pull to refresh is an essential functionality. It lets the user refresh the data on the screen when the user pulls the screen towards the bottom and loads new data.

Moreover, it 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. Then, new data becomes available at some point in time.

Two props are required to implement Pull to Refresh functionality in a React 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 React 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={() => }
/>
);
}
}

Conclusion on React Flatlist

That is it for React Flatlist component.

Now that you have learned about the React Flatlist component, you can fetch data from any API and display the list items in your app.

Above all, 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.

Are you looking for web development company?

ArrowHiTech is known as the leading IT Company in the world. So ArrowHiTech Services will help you get succeed in your business. For that reason, what are you waiting for? Let ArrowHiTech know your problem by entering your information into this CONTACT FORM. ArrowHiTech team working 24/7 will reply you soon. Moreover, in case you are confused with some services your need for your business. So let’s explore the amazing services at ArrowHiTech Website.

Tags

Share