Home » React-native » React-native GridView example using FlatList

React-native GridView example using FlatList

Pro Level React-native

In this article we going to learn about React-native GridView example using FlatList, This allows you to display data in proper manner like tow-dimensional view we can also increase columns of gridview, also it supports both android and iOS platform, it support Header and Footer support also we cannot use other libraries for pull to refresh it support pull to refresh, scroll loading, scroll to index, let’s take example

This is the basic syntax of FlatList:

<FlatList data={[{name: 'Tom'}, {name: 'Jerry'}]} 
renderItem={({item}) => <Text>{item.name}</Text>}

 numColumns={2} 
 />

This will display Tom and Jerry values of key name and numColumns={2} will render data in 2 columns like below

In this example we will make simple image gallery with two columns as seen below,

 <FlatList
       
          data={ this.state.JSONResult.product_list }
          
          ItemSeparatorComponent = {this.ItemSeparatorLine}
 
          renderItem={({item}) => 
          
         }
           numColumns={2}    //<---- add this line for GridView, if you remove this line then it will display ListView
          keyExtractor={(item, index) => index}
          
         />

To explain this in detail, we need to start with fetch call, to display data in FlatList

 

Fetch call

Create one method to call fetch API call and call this method componentDidMount() method of react-native this will call at app first-time start

constructor(props) {
super(props);
     this.getListCall= this.getListCall.bind(this);
     this.GetListItem= this.GetListItem.bind(this);
     this.state = { 
        JSONResult: "",
     }
}

componentDidMount(){
   this.getListCall();
}

getListCall(){
   var that = this;
   var url = "http://demo4059469.mockable.io/techup.co.in/getList";
   console.log("-----------url:"+url);

   fetch(url,{method: 'GET'}).then(function (response) {
    return response.json();
   }).then(function (result) {
     if(result.status.response === "success"){
      that.setState({ 
      JSONResult: result.data,
    });
  }
   console.log(result.data);
}).catch(function (error) {
   console.log("-------- error ------- "+error);
   alert("result:"+error)
});
}

Now our response JSON is as follows

{
  "status": {
    "response": "success",
    "message": "Product Fetch Successfully"
  },
  "data": { "product_list": [
    {
      "pid": "p001",
      "p_title": "First",
      "p_desc": "Tomatoes are a staple in Indian cuisines and across the world too. Fresho hybrid tomatoes are sourced from the best growers and ensure effective costs along with optimal health levels. These tomatsgoes are fresh and juicy in texture and they tend to last much longer than pure breed tomatoes.",
      "p_cat": 0,
      "p_imageurl": "https://techup.co.in/wp-content/uploads/2019/01/img_butterfly.jpg",
      "p_price": 9.00,
      "p_isnew": false,
      "p_likes": 150,
      "p_islike": false
    },
    {
      "pid": "p002",
      "p_title": "Second",
      "p_desc": "Onion is a vegetsgable which is almost like a staple in Indian food. This is also knosgwn to be one of the essesgntial ingredients of raw salads. They come in different colours like white, red or yellow and are quite in demsgand in cold salads and hsgot soups. You can dice, slice or cut it in rings and put it in burgers and sandwiches. Onions emit a sharp flavsgour and fragrance once they are fried; it is due to the sulpgshur compound in the vegetable.",
      "p_cat": 0,
      "p_imageurl": "https://techup.co.in/wp-content/uploads/2019/01/img_butterfly.jpg",
      "p_price": 15.00,
      "p_isnew": true,
      "p_likes": 200,
      "p_islike": false
    },
    {
      "pid": "p003",
      "p_title": "Third",
      "p_desc": "Fresho Potatoes are nutrient-dense, non-fattening and have reasonabsgle amount of calories. Include them in your regular meals so that the body receives a good supply of cagsrbohydrates, dietary fibers and essential minsgerals such as copper, magnsgesium, and iron. In India, potatoes are probably the second-most consumed vegetables after onions.",
      "p_cat": 0,
      "p_imageurl": "https://techup.co.in/wp-content/uploads/2019/01/img_butterfly.jpg",
      "p_price": 26.00,
      "p_isnew": true,
      "p_likes": 300,
      "p_islike": false
    }


    ]}
  }

To display these JSON data in gridview use FlatList as follows

before that, I suggest you install image loader library component by using the following command in the command line

npm install react-native-image-progress

npm install react-native-progress
  render() {

    return ( 
        <View style={styles.container}>

        <FlatList
       
          data={ this.state.JSONResult.product_list }
          
          ItemSeparatorComponent = {this.ItemSeparatorLine}
 
          renderItem={({item}) => 
          <TouchableOpacity activeOpacity={0.9} onPress={this.GetListItem.bind(this, item.p_title)}>
           <View style={styles.container} >
              
             <Image 
            source={{ uri: item.p_imageurl }} 
             indicator={ProgressBar} 
             indicatorProps={{
               size: 80,
               borderWidth: 0,
               color: 'rgba(150, 150, 150, 1)',
               unfilledColor: 'rgba(200, 200, 200, 0.2)'
            }}
               style={{
                width: 190, 
                  height: 190, 
                    alignItems: 'center',
                    margin: 5,
                    justifyContent: 'center',
            }}
            />


          <Text style={styles.welcome}  > {item.p_title} </Text>

            </View>
            </TouchableOpacity>

         }
           numColumns={2}    //<---- add this line for GridView, if you remove this line then it will display ListView
          keyExtractor={(item, index) => index}
          
         />
      </View>  
 
    );
  }
}

After json response data had successfully parse and saved this response in the state, then use that list from the response object in FlatList component

now we will be going to handle on click to do this we have to use the react-native TouchableOpacity onPress method its very simple create another method GetListItem and call this method as follows

 <TouchableOpacity activeOpacity={0.9} onPress={this.GetListItem.bind(this, item.p_title)}>

activeOpacity props handle onPress opacity animation

let’s see whole js file code so that we can understand clearly

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  ScrollView,
  TextInput,
  FlatList,
  Alert,
  TouchableOpacity,
} from 'react-native';



import Image  from 'react-native-image-progress';
import ProgressBar from 'react-native-progress';
import { StackNavigator } from 'react-navigation'

 

export default class App extends Component<Props> {


constructor(props) {
    super(props);
  this.getListCall= this.getListCall.bind(this);
  this.GetListItem = this.GetListItem.bind(this);
      this.state = { 
      JSONResult: "",
    }
  }

   componentDidMount(){
    this.getListCall();
  }

  getListCall(){
    var that = this;
    var url = "http://demo4059469.mockable.io/techup.co.in/getList";
    console.log("-----------url:"+url);

     fetch(url,{method: 'GET'}).then(function (response) {
        return response.json();
        }).then(function (result) { 

           if(result.status.response === "success"){

                that.setState({ 
              JSONResult: result.data,
              });
         
            }
           // console.log(result.data_list);
        }).catch(function (error) {
          console.log("-------- error ------- "+error);
         alert("result:"+error)
     });

  }

  GetListItem (name) {
   
  Alert.alert(name);
 
  }

  ItemSeparatorLine = () => {
    return (
      <View
        style={{
          height: .5,
          width: "100%",
          backgroundColor: "#111a0b",
        }}
      />
    );
  }
 



  render() {

    return ( 
        <View style={styles.container}>

        <FlatList
       
          data={ this.state.JSONResult.product_list }
          
          ItemSeparatorComponent = {this.ItemSeparatorLine}
 
          renderItem={({item}) => 
          <TouchableOpacity activeOpacity={0.9} onPress={this.GetListItem.bind(this, item.p_title)}>
           <View style={styles.container} >
              
             <Image 
            source={{ uri: item.p_imageurl }} 
             indicator={ProgressBar} 
             indicatorProps={{
               size: 80,
               borderWidth: 0,
               color: 'rgba(150, 150, 150, 1)',
               unfilledColor: 'rgba(200, 200, 200, 0.2)'
            }}
               style={{
                width: 190, 
                  height: 190, 
                    alignItems: 'center',
                    margin: 5,
                    justifyContent: 'center',
            }}
            />


          <Text style={styles.welcome}  > {item.p_title} </Text>

            </View>
            </TouchableOpacity>

         }
           numColumns={2}
          keyExtractor={(item, index) => index}
          
         />
      </View>  
 
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

 

React-native gridView example using FlatList
React-native gridView example using FlatList

Thank you 🙂 enjoy coding…

Related Posts

4 thoughts on “React-native GridView example using FlatList

  1. I’m still learning from you, but I’m making my way to the top as well. I definitely liked reading all that is written on your website.Keep the stories coming. I loved it!

Leave a Reply

Your email address will not be published. Required fields are marked *