In this React Native lesson we are going to learn about React Native FlatList, for example if you want to display list of items in react native than you can use flatlist, it is a performant interface for rendering basic, flat lists, supporting the most handy features like fully cross platform, optional horizontal mode, header support, footer support, pull to refresh, scrolling functionality and many more.
This is my ReactFlat.js component, you can see that we have created our FlatList.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import React from 'react' import {FlatList, Text} from 'react-native'; import {Card} from 'react-native-paper'; function ReactFlat() { const mydata = [ {id:1, title:"First Title", description:"First Description"}, {id:2, title:"Second Title", description:"Second Description"}, {id:3, title:"Third Title", description:"Third Description"}, {id:4, title:"Fourth Title", description:"Fourth Description"}, {id:5, title:"geekscoders.com", description:"Fourth Description"}, {id:6, title:"geekscoders.com", description:"Fourth Description"}, {id:7, title:"geekscoders.com", description:"Fourth Description"}, {id:8, title:"geekscoders.com", description:"Fourth Description"}, {id:9, title:"geekscoders.com", description:"Fourth Description"}, ] const renderData = (item) => { return( <Card style = {{padding:10, margin:10, backgroundColor:"#eddfdf"}}> <Text style = {{fontSize:25}}>{item.title}</Text> <Text style = {{fontSize:15}}>{item.description}</Text> </Card> ) } return ( <FlatList data = {mydata} renderItem = {({item}) => { return renderData(item) }} keyExtractor = {item => `${item.id}`} /> ) } export default ReactFlat |
In the FlatList you need to give your data, renderItem, in the renderItem we want to give our method that we have already created and the last one is the keyExtractor and it tells the list to use the id for the react keys instead of the default key property.
1 2 3 4 5 6 7 8 9 |
<FlatList data = {mydata} renderItem = {({item}) => { return renderData(item) }} keyExtractor = {item => `${item.id}`} /> |
This is our method basically we are going to just render the title and description of our data in a Card component.
1 2 3 4 5 |
<Card style = {{padding:10, margin:10, backgroundColor:"#eddfdf"}}> <Text style = {{fontSize:25}}>{item.title}</Text> <Text style = {{fontSize:15}}>{item.description}</Text> </Card> |
First run this command to start your metro bundler.
1 |
npm start |
Now you can run your application.