FlatList in React Native
The world’s latest technologies, policies, business-boosting strategies will be written here. Contact Morosoft

One of the most commonly used UI features in mobile apps is the scrollable list. As most of the apps need to display a large amount of the data and it is only possible through the list due to the narrow screen of the mobile.



React Native also has some components that are used to display such a list and views. Flatlist in React Native is one of the best component to render these long data list.

[ultimate_heading main_heading=”What is FlatList ?” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

What is the Flatlist component? It is an easy way to make an efficient scrolling list of data. It has not only great features but also a simple and efficient API to work with. If you have ever used or are familiar with the ListView, then you have noticed that it’s a lot better in almost every way.

[ultimate_heading main_heading=”What are amazing features of FlatList in React Native?” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

It has some awesome features that includes:
1) Pull to refresh.
2) Load more
3) On End Reached
4) Progress View Offset
5) List Header Component
6) List Footer Component

Now let’s move to the most awaited part.
In this article, we will use Random User Generator API for the data and Native Base Element to implement the interface.
In ComponentDidMount we will make our remote request.
Code for the constructor for our

 constructor(props) {
super(props)
console.log(this.props)

this.state = {
dataLoading: false,
data: [],
page: 1,
seed: 1,
error: null,
}
}

We will use fetch for the API calls in our ComponentDidMounts() life cycle to get user data.

   componentDidMount() {
    this.fetchUserData();
  }

  fetchUserData = () => {
    const { page, seed } = this.state;
    const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=10`;
    this.setState({ dataLoading: true });

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: page == 1 ? res.results : [...this.state.results, ...res.results],
          dataLoading: false,
          refreshing: false
        })
      })
      .catch(error => {
        alert('Something went wrong');
        this.setState({
          dataLoading: false
        })
      })
  }

After that we will display an activity indicator to show user about some processing that data is still being loaded.


{this.state.dataLoading && (
          <View style={styles.mainContainer}>
            <ActivityIndicator size=&quot;large&quot; color=&quot;red&quot; />
          </View>
        )}

There is a check at the top that make sure that data is loaded completely, and once the data is completely load we set the state of dataLoading to false to show complete list to use.
After that I used FlatList component to display list and Pass an array of data to the FlatList via the data prop.


<List>
            <FlatList data={this.state.data} />
</List>

After that, we have to render the content with the renderItem prop. You have to pass a single object so you have to destructure so that you can access it from within the function.

     {!this.state.dataLoading && (
          <List>
            <FlatList data={this.state.data} renderItem={({ index, item }) => (
                <ListItem key={index}>
                    <Text>{item.name.first}</Text>
                </ListItem>
              )}
            />
          </List>
        )}

After that you will have an application like this.

Let’s take this application to the next level. Now we will add thumbnail to the left of it, email and view more button on the right side.




    {!this.state.dataLoading && (

             (

                    {item.name.first}
                    {item.email}

                    <button>
                      View
                    </button>

              )}
            />

        )}

Now our application will look like this.

[ultimate_heading main_heading=”How to add header through Flatlist” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

Let’s render a component at the top of the list that is called header and use search bar element from native base.

First create a function that renders the header component.

  headerBar = () => {
    return (


<Header searchBar rounded>
        <Item>
          <Icon name=&quot;ios-search&quot; />
          <Input placeholder=&quot;Search&quot; />
          <Icon name=&quot;ios-people&quot; />
        </Item>
        <Button transparent>
          <Text>Search</Text>
        </Button>
      </Header>


    )
  }

Now you can render the header component using ListHeaderComponent prop on flatlist.

<FlatList data={this.state.data} keyExtractor={item => item.email}
              ListHeaderComponent={this.headerBar}/>

Now it will look like this.

[ultimate_heading main_heading=”Pull to refresh in Flatlist” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

Now let’s use another amazing feature of FlatList in React Native component that is pull to refresh. Pull to refresh is use to load new data in your application API.

[ultimate_heading main_heading=”How pull to refresh works?” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

Basically when someone pulls down the list a remote request to API is called and it checks whether there is new data or not and if new data is found it automatically loads in the UI of the app. Most of the apps like messenger and WhatsApp uses this functionality.
Let’s add a state refreshing and set this to value to false by default. Now your constructor will look like this.

constructor(props) {
    super(props)
    console.log(this.props)

    this.state = {
      dataLoading: false,
      data: [],
      page: 1,
      seed: 1,
      error: null,
      refreshing: false

    }
  }

Now add a function handleRefresh() that will handle all the apps state when someone pulls his screen down.

  handleRefresh = () => {
    this.setState({
      page: 1,
      refreshing: true,
      seed: this.state.seed + 1,
    }, () => {
      this.fetchUserData()
    })
  }

In this function we update our states and set refreshing to true that will render the FlatList again and on his call back we are simply calling the fetchUserData() function again with new states

Now we have to add two props refreshing that accepts a Boolean value and onRefresh in which we pass handleRefresh function as a refrence.

Our final code will look like this.

        {!this.state.dataLoading && (
          <List>
            <FlatList data={this.state.data} keyExtractor={item => item.email}
              ListHeaderComponent={this.headerBar}
              refreshing={this.state.refreshing}
              onRefresh={this.handleRefresh}
              renderItem={({ index, item }) => (
                <ListItem thumbnail key={index}>
                  <Left>
                    <Thumbnail rounded source={{ uri: item.picture.thumbnail }} />
                  </Left>
                  <Body>
                    <Text>{item.name.first}</Text>
                    <Text style={{ fontSize: 13 }}>{item.email}</Text>
                  </Body>
                  <Right>
                    <Button transparent>
                      <Text>View</Text>
                    </Button>
                  </Right>
                </ListItem>
              )}
            />
          </List>
        )}

FlatList has a bunch of other interesting options which you can find in a documentation page.

To enhance your knowledge regarding advanced technologies tune to Morosoft tweaks https://www.mstweaks.com/.
If you want to be up to date with all what is happening in the world, Morosoft Tweaks is providing you all under one roof. We also aim to provide relevant information in a quick and sophisticated manner. Therefore you can contact us: info@morosoft.pk.

LEAVE A REPLY

Please enter your comment!
Please enter your name here