Gaurav Singhal Guarav is a data scientist with a strong background in computer science and mathematics. As a developer, he works with Python, Java, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React.

How to use the FlatList component in React

5 min read 1430

React Native logo.

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.

An introduction to flatList component

The 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.

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 FlatList component from react-native and use it to display the countries:

We made a custom demo for .
No really. Click here to check it out.

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. 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

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

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>
    );
  }
}

Conclusion

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.

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Gaurav Singhal Guarav is a data scientist with a strong background in computer science and mathematics. As a developer, he works with Python, Java, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React.

Leave a Reply