Simple flatlist example in react native

flatlistreactnative
Image source:Pixabay

Flatlist is new component introduced in recent version of react native along with sectionlist for rendering list based data in react native screens.Going by the official documentation the advantages of using this component are:

  • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen
  • Pull to refresh functionality

In today’s article we are going to implement flatlist in react native.

First make sure that you have latest version of react native installed. My current package.json contains following versions of react native and react installed:

The code for implementing flatlist is pretty straight forward:-

Here we pass a jsonArray as data prop and define how each individual list item is to be rendered in renderItem prop.

For example in my case , the data prop has the following format:

So we define renderFlatListItem function as follows:

Here we are rendering simple nested view components with topic category at the top followed by gridview containing topic items.The end result looks like this:

There are several additional options for customizing flatlist as follows:

  • horizontal(boolean): Set it to true if you need render horizontally scrollable flatlist
  • numColumns(number):Set no of columns when horizontal is set to false for vertically scrollable list
  • onEndReached(funtion):Event listener which is triggered when user scrolls to end of the list. We can use this function to show a loader and append more list items at the end of the list
  • refreshing(boolean): Set this true while waiting for new data from a refresh.
  • onRefresh: If provided, a standard RefreshControl will be added for “Pull to Refresh” functionality. Make sure to also set the refreshing prop correctly.
  • ItemSeparatorComponent(ReactClass): You can specify the component to be rendered in between listitems like line separators using this option
  • ListFooterComponent(ReactClass):You can specify the component at the end of list using this option
  • ListHeaderComponent(ReactClass):You can specify the component to be rendered at the top of the list

There are also some more options and methods available which can try from the official documentation here. That brings us to end of today’s short tutorial.

Connect Deeper:

In the next article I will cover how to handle navigation between application screens using reactnavigation npm module. In order to get notified about future posts you can follow on facebook: Technoetics or subscribe to our mailing list below:

Technoetics newsletter

Get notified about upcoming articles,tips and tricks personally hand-delivered to your inbox

 

 

Share post-
About Saurabh Mhatre 70 Articles
Currently working in web and hybrid application development