Using Lists in Snack


Sometimes, the task is to store and display several items as a List. For this React Native component, Flatlist can be used. The FlatList can also be made selectable or clickable. In this article, the React native and javascript code is shown with two different examples where first the items of a list are stored as an array of key-value pairs identifiable with a unique id and then fetched and rendered.

Algorithm

Algorithm-1

Step 1 − Import FlatList, Text and View from 'react-native'.

Step 2 − Make the App.js and write the code for storing a list. The list is in form of an array but stored as key-value pairs. Each item has a unique id.

Step 3 − Make an arrow function “showlist” to set the state to contain all the list items.

Step 4 − Fetch the state variable list and render all items one by one.

Step 5 − To display the items on the screen View and Text are used with desired styles.


Example 1: Displaying all the items in a Flatlist.

The important file used in the project is

  • App.js

App.js : This is the main javascript file for this project.

Example

import React from 'react';
import {FlatList,Text, View} from 'react-native';

export default class FetchExample extends React.Component {
   constructor(props){
      super(props);
      this.state ={
         list:[
            {
               "id": 1,
               "name": "Sector 15 A",
               "city": "Faridabad",
               "lat": 28.395403,
               "lng": 77.315292,
            },
            {
               "id": 2,
               "name": "Borivali",
               "city": "Mumbai",
               "lat": 19.228825,
               "lng": 72.854118,
            },
            {
               "id": 3,
               "name": "Kolutolla",
               "city": "Kolkata",
               "lat": 22.578005,
               "lng": 88.358536,
            },
            {
               "id": 4,
               "name": "Benz Circle",
               "city": "Vijayawada",
               "lat": 16.499725,
               "lng": 80.656067,
            },
         ],
         keyid:0,
      }
   }
   showitem= ()=>{
      for(var i=0;i<this.state.list.length;i++){
         this.setState({keyid:this.state.keyid+1})
      }
   }
   render(){
      return(
         <View style={{flex: 1, paddingTop:5, backgroundColor: 'forestgreen'}}>
            <Text style={{padding:60,fontSize: 18,       fontWeight: 'bold'}}>Latitude and Longitude</Text>
            <View style={{flexDirection:'row', justifyContent: 'space-between',
            alignItems:'center', padding:10, backgroundColor: 'brown', margin: 10}}>
               <Text style={{fontSize: 18, fontWeight: 'bold'}}>Place</Text>
               <Text style={{fontSize: 18, fontWeight: 'bold'}}>City</Text>
               <Text style={{fontSize: 18, fontWeight: 'bold'}}>Latitude</Text>
               <Text style={{fontSize: 18, fontWeight: 'bold'}}>Longitude</Text>
            </View>
            <FlatList
            data={this.state.list}
            renderItem={({item}) => (
               <View style={{flexDirection:'row', justifyContent: 'space-between',
               alignItems:'center', padding:10, backgroundColor: 'lawngreen', margin: 10}}>
                  <Text>{item.name}</Text>
                  <Text>{item.city}</Text>
                  <Text>{item.lat}</Text>
                  <Text>{item.lng}</Text>
               </View>
            )}
            keyExtractor={(item, index) => index}
            />
         </View>
      );
   }
}

Viewing The Result

The result can be seen online. As the user types in the code, the Web view is selected by default and the result appears instantly.

Flatlist items showing in the Web view in Snack

Algorithm-2

Step 1 − Import FlatList, TouchableOpacity Alert, Text and View from 'react-native'.

Step 2 − Make the App.js and write the code for storing a list. The list is in form of an array but stored as key-value pairs. Each item has a unique id.

Step 3 − Make an arrow function “showlist” to set the state to contain all the list items.

Step 4 − Fetch the state variable list and render all items one by one.

Step 5 − To make the Flatlist items clickable, TouchableOpacity is used with desired styles.

Step 6 − The function onPress() specifies the action to be taken when a list item is clicked. For example, here the latitude and longitude values as result are displayed in the alert after converting the JSON object as text.

Example 2: Making the items in a Flatlist clickable to show results specific to the selected item.

The Important file used in the project is

  • App.js

App.js : This is the main javascript file for this project.

Example

import React from 'react';
import {Alert, FlatList,Text, View,TouchableOpacity} from 'react-native';

export default class FetchExample extends React.Component {
   constructor(props){
      super(props);
      this.state ={ 
         list:[
            {
               "id": 1,
               "name": "Sector 15 A",
               "city": "Faridabad",
               "lat": 28.395403,
               "lng": 77.315292,
            },
            {
               "id": 2,
               "name": "Borivali",
               "city": "Mumbai",
               "lat": 19.228825,
               "lng": 72.854118,
            },
            {
               "id": 3,
               "name": "Kolutolla",
               "city": "Kolkata",
               "lat": 22.578005,
               "lng": 88.358536,
            },
            {
               "id": 4,
               "name": "Benz Circle",
               "city": "Vijayawada",
               "lat": 16.499725,
               "lng": 80.656067,
            },
         ],
         keyid:0,

      }
   }
   showitem= ()=>{
      for(var i=0;i<this.state.list.length;i++){
         this.setState({keyid:this.state.keyid+1})
      } 
   }
   render(){
      return (
            <View style={{flex: 1, paddingTop:5, backgroundColor: 'forestgreen'}}>
            <Text style={{padding:60,fontSize: 18, fontWeight: 'bold'}}>Latitude and Longitude</Text>
            <View style={{flexDirection:'row', justifyContent: 'space-between',
            alignItems:'center', padding:10, backgroundColor: 'brown', margin: 10}}>
            <Text style={{fontSize: 18, fontWeight: 'bold'}}>Place</Text>
            <Text style={{fontSize: 18, fontWeight: 'bold'}}>City</Text>
            <Text style={{fontSize: 18, fontWeight: 'bold'}}>Latitude</Text>
            <Text style={{fontSize: 18, fontWeight: 'bold'}}>Longitude</Text>
         </View>
          
         <FlatList
         data={this.state.list}
         renderItem={
         ({item ,index}) => (
            <View style={{flex: 1, flexDirection:'row', justifyContent: 'space-between', alignItems:'center', padding:10, backgroundColor: 'lawngreen', margin: 10}}>
               <TouchableOpacity 
                  key={index.toString()} 
                  onPress={() =>{
                     let str= JSON.stringify(item.name);
                     let str1 = JSON.stringify(item.lat);
                     let str2 = JSON.stringify(item.lng);
                     Alert.alert(str +" --" + "latitude: " +str1+ "" + "
longitude: " +str2); //alert(str +" --" + "latitude: " +str1+ "" + "
longitude: " +str2); } } > <Text>{item.name}</Text> <Text>{item.city}</Text> </TouchableOpacity> </View> ) } keyExtractor={(item, index) => index} /> </View> ); } }

Viewing the Result

The result can be seen online. As the user types in the code, the Web view is selected by default and the result appears instantly. Alert.alert() function may not show the result in the Web view. So, to see the results, a simple alert() can be used. Both statements are shown in the code example. One of these can be kept as a comment.

Flatlist clickable item showing a simple alert on personal mobile on selecting an item

Flatlist clickable item showing Alert on personal mobile

In this article, using two different examples, the way to show a Flatlist on Expo Snack is given. First the method given for storing the list items and then the process of fetching the listitems and showing these as Flatlist are given. The method of selecting and performing an action on clicking a Flatlist item is also specified in example 2. Also, the output on the online web view and the personal mobile device is shown.

Updated on: 02-May-2023

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements