FlatList Data with id and value pairs in react-native expo

Before Started:

You should have basic knowledge about FlatList, if you not have then read in here

Wanted:

I want to make a list with id value pair like¬†¬†{ id: ‘1’, text: ‘Menuju Masjid’ } and if i press the list item then it show alert with id:value information like image below:

flatlist_idvalue
 

Question:

How to make it … ?

Answer:

We will do two step:

  • Create a listDoa file for defining FlatList
  • Modify App.js File

 

Create a listDoa File

Create listDoa filename inside views folder and add this code below:

import React,{ Component } from ‘react’;
import { FlatList, Text, StyleSheet, View } from ‘react-native’;

const baris = [

{ id: ‘1’, text: ‘Menuju Masjid’ },
{ id: ‘2’, text: ‘I\’tikaf di Masjid’ },
{ id: ‘3’, text: ‘Keluar Masjid’ },

]

const extractKey = ({id})=>id

export default class ListDoa extends Component {

klik=(isi)=>{

alert(isi.id+”:”+isi.text)

}
render() {

return (

<View style={styles.container}>

<FlatList

data={baris}
keyExtractor={extractKey}
renderItem={({item}) =>
<Text style={styles.tengah} onPress={this.klik.bind(this,item)}>{item.text}</Text>}

/>

</View>
)

}

}

const styles = StyleSheet.create({

container: {

flex: 1,
paddingTop: 30,

},
tengah:{

height:44,
textAlign:’center’,
marginBottom:1,
paddingTop:10,
fontSize:16,
backgroundColor:’#CCC’

}

});

Explain:

  • const baris, this code mean that i create a variable called baris, this baris variable value cannot be changed
  • klik=(isi)=>, this code mean that i create a function called klik which has an isi argument
  • keyExtractor={extractKey}, this code is used to give id to FlatList data
  • onPress is the event occured when we press the list item
  • this.klik.bind(this,item), bind in this code to make sure the klik function execute after the list item get pressed

Modify App.js

Modify App.js like this code below:

import React from ‘react’;
import ListDoa from ‘./views/listDoa’;

const App = () => {
return (
<ListDoa />
)
}export default App;

 

Thanks For Reading

You may also like...

Leave a Reply

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