FlatList React Native

Introduction 
 
Here, I am going to explain how we can create a simple list using React-Native so that it will work in both iOS and Android applications. I have already given a basic introduction about react-native, those who want to check can click here. In this article, I will be explaining how to fetch data from API and show the results in a List (RecyclerView in Android, UITableView in iOS). Please go through the introductory article for the initial setups.
 
First, create the project using the following command,
  • react native init <projectName>
  • react-native init ListSample
This will create the project, which will contain Android and iOS folders.
 
FlatList React Native 
 
Open the App.js file which will be an entry point of React-Native applications. This file will contain- 
  1. import React, {  
  2.     Component  
  3. } from 'react';  
  4. import {  
  5.     Platform,  
  6.     StyleSheet,  
  7.     Text,  
  8.     View  
  9. } from 'react-native';  
  10. const instructions = Platform.select({  
  11.     ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',  
  12.     android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu',  
  13. });  
  14. type Props = {};  
  15. exportdefaultclass App extends Component < Props > {  
  16.     render() {  
  17.         return ( < View style = {  
  18.             styles.container  
  19.         } > < Text style = {  
  20.             styles.welcome  
  21.         } > Hello World < /Text> < /View > );  
  22.     }  
  23. }  
  24. const styles = StyleSheet.create({  
  25.     container: {  
  26.         flex: 1,  
  27.         justifyContent: 'center',  
  28.         alignItems: 'center',  
  29.         backgroundColor: '#F5FCFF',  
  30.     },  
  31.     welcome: {  
  32.         fontSize: 20,  
  33.         textAlign: 'center',  
  34.         margin: 10,  
  35.     },  
  36.     instructions: {  
  37.         textAlign: 'center',  
  38.         color: '#333333',  
  39.         marginBottom: 5,  
  40.     },  
  41. });  
Delete the entire thing, we really don't need to import the header files,
  1. importReact, {Component} from'react';  
  2. import { StyleSheet, Text, View,FlatList,TouchableOpacity,ActivityIndicator} from'react-native';  
FaltList is similar to Android recyclerview; it shows a similar kind of data as an ActivityIndicator list. It is also the same in Android, which will show an indefinite progress bar while we are fetching data from API TouchableOpacity. It will be the new component which will make a view as touchable.
 
Here, I am taking the same API which is mentioned in the official documentation of react-native
 
https://facebook.github.io/react-native/movies.json
 
This will return a JSON like,
  1. {  
  2.     "title""The Basics - Networking",  
  3.     "description""Your app fetched this from a remote endpoint!",  
  4.     "movies": [{  
  5.         "id""1",  
  6.         "title""Star Wars",  
  7.         "releaseYear""1977"  
  8.     }, {  
  9.         "id""2",  
  10.         "title""Back to the Future",  
  11.         "releaseYear""1985"  
  12.     }, {  
  13.         "id""3",  
  14.         "title""The Matrix",  
  15.         "releaseYear""1999"  
  16.     }, {  
  17.         "id""4",  
  18.         "title""Inception",  
  19.         "releaseYear""2010"  
  20.     }, {  
  21.         "id""5",  
  22.         "title""Interstellar",  
  23.         "releaseYear""2014"  
  24.     }]  
  25. }  
First, we need to fetch the data from API and then show the movies object as a list.
 
For this, there is a method named.Which is a life cycle method and it will get executed after the render() method. From the official documentation, the life-cycle methods of a react-native application are as follows-
In the constructor, we will initialize a variable isLoading as true to the state. So the constructor will look like- 
  1. constructor(props) {  
  2.     super(props);  
  3.     this.state = {  
  4.         isLoading: true  
  5.     }  
  6. }  
As per the documentation after the constructor, the render method will get executed. So in render(), we will check whether the isLoading is true. If true then we will show the Activity indicator on the UI, so that the user will be aware that there are some operations happening in the App.
  1. render() {  
  2.         if (this.state.isLoading) {  
  3.             return ( < Viewstyle = {  
  4.                 {  
  5.                     flex: 1,  
  6.                     padding: 20  
  7.                 }  
  8.             } > < Textstyle = {  
  9.                 styles.welcome  
  10.             } > Loading < /Text> < ActivityIndicator / > < /View>)  
  11.         }  
Now, will call the API and once we get the response we will set the isLoading to false and the datasource as movie object from the response.
  1. componentDidMount() {  
  2.     returnfetch('https://facebook.github.io/react-native/movies.json').then((response) => response.json()).then((responseJson) => {  
  3.         this.setState({  
  4.             isLoading: false,  
  5.             dataSource: responseJson.movies,  
  6.         }, function() {});  
  7.     }).catch((error) => {  
  8.         console.error(error);  
  9.     });  
  10. }  
Now, we need to create each item in the list. For that create a class named MyListItem, which will have the items which need to be populated for each list row.
  1. classMyListItemextendsReact.PureComponent {  
  2.     _onPress = () => {  
  3.         this.props.onPressItem(this.props.id);  
  4.     };  
  5.     render() {  
  6.         return ( < TouchableOpacityonPress = {  
  7.                 this._onPress  
  8.             } > < Viewstyle = {  
  9.                 styles.listItemView  
  10.             } > < Textstyle = {  
  11.                 styles.headerText  
  12.             } > {  
  13.                 this.props.title  
  14.             } < /Text> < Textstyle = {  
  15.                 {  
  16.                     color: "black"  
  17.                 }  
  18.             } > {  
  19.                 this.props.description  
  20.             } < /Text> < Viewstyle = {  
  21.                 styles.dividerView  
  22.             }  
  23.             /> < /View> < /TouchableOpacity>);  
  24.     }  
  25. }  
Here, we have two text views and a divider at the bottom. We will show the film name and release year for each movie and a divider at the bottom. For that we defined some styles as well to customize each items.
  1. conststyles = StyleSheet.create({  
  2.     container: {  
  3.         flex: 1,  
  4.         justifyContent: 'center',  
  5.         alignItems: 'center',  
  6.         backgroundColor: '#F5FCFF',  
  7.     },  
  8.     welcome: {  
  9.         fontSize: 20,  
  10.         textAlign: 'center',  
  11.         margin: 10,  
  12.         color: 'green'  
  13.     },  
  14.     listItemView: {  
  15.         padding: 5,  
  16.         flexDirection: 'column'  
  17.     },  
  18.     headerText: {  
  19.         color: "red",  
  20.         fontWeight: 'bold',  
  21.         textAlign: 'left',  
  22.         fontSize: 20  
  23.     },  
  24.     dividerView: {  
  25.         borderBottomColor: 'black',  
  26.         borderBottomWidth: 1  
  27.     }  
  28. });  
Now, in the render() else part(whch means isLoading = false) we will show a FlatList, create a FlatList as below.
  1. return ( < View > < Textstyle = {  
  2.         styles.welcome  
  3.     } > Welcome < /Text> < FlatList data = {  
  4.         this.state.dataSource  
  5.     }  
  6.     renderItem = {  
  7.         this._renderItem  
  8.     }  
  9.     /> < /View>);  
This will have data and renderItem. Data will be the JSON data which we got from the API response that we saved in the state. Datasource variable and the renderItem will be a function in which we can decide which data would be shown in which Textview.
  1. _renderItem = ({  
  2.     item  
  3. }) => ( < MyListItem id = {  
  4.         item.id  
  5.     }  
  6.     title = {  
  7.         item.title  
  8.     }  
  9.     description = {  
  10.         item.releaseYear  
  11.     }  
  12.     />);  
Which will set Id, title and descriptin to MyListItem class which we are rending in MyListItem class
  1. <Textstyle= {styles.headerText}> {this.props.title} </Text>  
  2.     <Textstyle= {{ color:"black" }}> {this.props.description} </Text>  
That's it, so the entire file would look like.
  1. importReact, {  
  2.     Component  
  3. }  
  4. from 'react';  
  5. import {  
  6.     StyleSheet,  
  7.     Text,  
  8.     View,  
  9.     FlatList,  
  10.     TouchableOpacity,  
  11.     ActivityIndicator  
  12. } from 'react-native';  
  13. exportdefaultclassAppextendsComponent {  
  14.     constructor(props) {  
  15.         super(props);  
  16.         this.state = {  
  17.             isLoading: true  
  18.         }  
  19.     }  
  20.     componentDidMount() {  
  21.         returnfetch('https://facebook.github.io/react-native/movies.json').then((response) => response.json()).then((responseJson) => {  
  22.             this.setState({  
  23.                 isLoading: false,  
  24.                 dataSource: responseJson.movies,  
  25.             }, function() {});  
  26.         }).catch((error) => {  
  27.             console.error(error);  
  28.         });  
  29.     }  
  30.     _renderItem = ({  
  31.         item  
  32.     }) => ( < MyListItem id = {  
  33.             item.id  
  34.         }  
  35.         title = {  
  36.             item.title  
  37.         }  
  38.         description = {  
  39.             item.releaseYear  
  40.         }  
  41.         />);  
  42.     render() {  
  43.         if (this.state.isLoading) {  
  44.             return ( < Viewstyle = {  
  45.                 {  
  46.                     flex: 1,  
  47.                     padding: 20  
  48.                 }  
  49.             } > < Textstyle = {  
  50.                 styles.welcome  
  51.             } > Loading < /Text> < ActivityIndicator / > < /View>)  
  52.         }  
  53.         return ( < View > < Textstyle = {  
  54.                 styles.welcome  
  55.             } > Welcome < /Text> < FlatList data = {  
  56.                 this.state.dataSource  
  57.             }  
  58.             renderItem = {  
  59.                 this._renderItem  
  60.             }  
  61.             /> < /View>);  
  62.     }  
  63. }  
  64. classMyListItemextendsReact.PureComponent {  
  65.     _onPress = () => {  
  66.         this.props.onPressItem(this.props.id);  
  67.     };  
  68.     render() {  
  69.         return ( < TouchableOpacityonPress = {  
  70.                 this._onPress  
  71.             } > < Viewstyle = {  
  72.                 styles.listItemView  
  73.             } > < Textstyle = {  
  74.                 styles.headerText  
  75.             } > {  
  76.                 this.props.title  
  77.             } < /Text> < Textstyle = {  
  78.                 {  
  79.                     color: "black"  
  80.                 }  
  81.             } > {  
  82.                 this.props.description  
  83.             } < /Text> < Viewstyle = {  
  84.                 styles.dividerView  
  85.             }  
  86.             /> < /View> < /TouchableOpacity>);  
  87.     }  
  88. }  
  89. conststyles = StyleSheet.create({  
  90.     container: {  
  91.         flex: 1,  
  92.         justifyContent: 'center',  
  93.         alignItems: 'center',  
  94.         backgroundColor: '#F5FCFF',  
  95.     },  
  96.     welcome: {  
  97.         fontSize: 20,  
  98.         textAlign: 'center',  
  99.         margin: 10,  
  100.         color: 'green'  
  101.     },  
  102.     listItemView: {  
  103.         padding: 5,  
  104.         flexDirection: 'column'  
  105.     },  
  106.     headerText: {  
  107.         color: "red",  
  108.         fontWeight: 'bold',  
  109.         textAlign: 'left',  
  110.         fontSize: 20  
  111.     },  
  112.     dividerView: {  
  113.         borderBottomColor: 'black',  
  114.         borderBottomWidth: 1  
  115.     }  
  116. });  
Go to the project folder from the command line and run the command react-native start and open the Android folder in Android studio and run that project like a normal Android application. You can see the output:
 
FlatList React Native 
 
The app is trying to fetch data from API, once it's done,
 
FlatList React Native 
 
Happy coding, cheers.


Similar Articles