How to implement a very basic Flatlist in React-Native

Alex
5 min readJul 21, 2019

--

This is my FIRST story/article on “Medium” so i hope people will play nice ;) haha, I am a software developer in the UK and one of the technologies I am interested outside of my job is React-Native, so i wanted to start writing articles or tutorials about this topic to help others and to help my own understanding of React-Native too. This tutorial will just be a basic implementation of the “Flatlist” component found in React-Native as well as an explanation of what a “Flatlist” is, nothing more, nothing less, so let us begin.

We must first create a react native project, to do this open a terminal and locate to anywhere on your computer, I usually put my projects in the “downloads” folder and enter the command.

react-native init nameOfprojectgoeshere

This will begin to create a react native project including all the necessary files, once this is done, open your chosen code editor (I like VS code) and open the project folder within the editor. You should see a bunch of files with names like “App.js” and “package.json” on the left hand side, open “App.js”, this is where the code for our “FlatList” will go, to run the react-native app, use either the command “react-native run-ios” or react-native run-android”.

A “FlatList” is a component that displays a list of data in a structured and scrollable manner, it is an improvement on the “ScrollView” component in a number of ways including the method in which both of them renders data, “ScrollView” renders every item of data at once, which may seem easy, however, if you have thousands of pieces to data to render to the screen then this can potentially lead to poor performance and slow rendering, meanwhile, the “FlatList” renders the items (and this is a term I love) “lazily” in that it only renders items that show on the screen to the user and removes the items that aren’t showing to the user from memory thus improving performance and using a lot less memory.

Furthermore, there are 2 mandatory methods to implement when creating a “Flatlist” one being “data” and the other being “renderItem”. “data” is the data that you want to show to the user on the “FlatList", and “renderItem” is formatting of that data i.e. you may want the data to show in a text element with specific styling, you can do this within the “renderItem” prop itself, or you can create a method that returns the styling you want and reference the method like so “renderItem={this.flatListRenderExample}” (I prefer returning a method personally).

Just a thought for when you next have a debate in the office or at home as to which component to use for your world-changing app!

To implement the “Flatlist” into your React-Native app (Assuming you have already creating your react-native project using “react-native init InsertAwesomeProjectNameHere”) you will have to add “FlatList” to the “React-Native” import statement as shown below.

import {SafeAreaView,StyleSheet,ScrollView,View,Text,StatusBar,FlatList} from 'react-native';

And from this you can now begin to use the “FlatList” component within the page you imported it to, in addition, usually with a “FlatList” component the data will be from the apps “State” which is found in the constructor of the component as shown in the code below.

constructor(props){super(props);this.state = {FlatListItems: [{name:'Patrick star'},{name:'Gallileo'},{name:'Einsten'},{name:'Peterson'},{name:'Schwarzenneger'},{name:'Dostoyevsky'}],};}

As you can see I have a state value of “FlatListItems” which contains an array of objects with a key of “name” of some of my favourite people!

NOTE: With a lot of applications the data in a “FlatList" is retrieved from some sort of API (Whether it be Google, OpenWeather or even your own) so it helps to populate the “FlatList” within the correct React lifecycle method, and for retrieving information from APIs that method would be “componentDidMount”, I will explain all of the lifecycle methods in a different article.

You can copy the state that i have or make your own, but make sure it is in the same format i.e. array of objects. Next I will show you a basic implementation of the “Flatlist”.

<FlatListstyle={{marginTop:40}}data={this.state.FlatListItems}renderItem={({item})=>(<View style={{justifyContent:'center',marginBottom:10}}><Text style={{backgroundColor:'blue',color:'white',padding:10,width:Dimensions.get('window').width}}>{item.name}</Text></View>)}/>

As you can see I have done some incredibly basic styling with “margin” and “justifyContent” and within the renderItem you pass it an object and call it whatever you like, in this instance I have named it “item”, with this you can reference the data that will be shown on the screen and access specific pieces of it, in the above example I am accessing the “name” key of the array of objects “flatListItems” and putting it inside a “Text” component.

Incredibly ugly flatlist

Above is the output of the above code and as you can see it is incredibly basic with a hint of colour, you can be a lot fancier with this by implementing a package called “react-native-elements” which has a “Card” component which looks great on flatlists!

If you want an alternative way to build the renderItem method you can create your own custom method like below and reference it in the “FlatList” component.

_renderMyList = ({item})=>(<View style={{justifyContent:'center',marginBottom:10}}><Text style={{backgroundColor:'blue',color:'white',padding:10,width:Dimensions.get('window').width}}>{item.name}</Text></View>)<FlatListstyle={{marginTop:40}}data={this.state.FlatListItems}renderItem={this._renderMyList}/>

However, with this in mind, if you have managed to get this far you may see an idiosyncratic yellow error on the bottom of your simulator which is along the lines of “VirtualizedList: missing keys for items” this indicates that there is no unique identifier for each record within the flatlist, to do this all we will need to do is add another object to the state data, something like “id” and ensure that each value is unique, then this warning will go.

So the state data will need to be updated to the below.

this.state = {FlatListItems: [{name:'Patrick star',id:"1"},{name:'Gallileo',id:"2"},{name:'Einsten',id:"3"},{name:'Peterson',id:"4"},{name:'Schwarzenneger',id:"5"},{name:'Dostoyevsky',id:"6"}],};

Strangely, the key identifier needs to be of type string, not number, in addition, we also need to include another method in the “Flatlist” component called “keyExtractor” and this is much the same as renderItem in that you can write the code necessary inside of the “keyExtractor” property or write a function to return the value, I have gone for the latter as you can see below which takes 2 arguments, the index of the row and the item of the row.

_renderMyKeyExtractor=(item,index)=>item.id.toString();

Even though my data is already a string, if you are retrieving from an API, the value/unique ID may not be in string format, so you can use “toString” to turn the returned value into a string. As you can see as well I am referring the “id” key of the object if I called it “dataId” I would refer to it as such “item.dataId.tosString()”.

So now my FlatList” code looks like this.

<FlatListstyle={{marginTop:40}}data={this.state.FlatListItems}renderItem={this._renderMyList}keyExtractor={this._renderMyKeyExtractor}/>

And this warning has now magically disappeared!

Thank you for reading my article any feedback, constructive criticism or clap/like ;) is appreciated.

--

--