React Native - FlatList - Mobile App Development
Felicitations! You are standing in the right place! In this example, we provide hardcoded elements to the data prop. Each element in the data props is rendered as a Text component.
Our screen will look like this −
Implementation
First, You must set up your local development environment. Follow the below link to set up your local environment.
After executing the commands mentioned in this link, a folder with a specified name is created with the following contents.
import React from 'react';
import { StyleSheet, FlatList, Text, View, Alert } from 'react-native';
Engender constructor in our main class. Using this.state we are defining the FlatList items array with key
constructor(props) {
super(props);
this.state = {
ListItems: [
{ key: 'Javacsript' },
{ key: 'jQuery' },
{ key: 'Angular' },
{ key: 'ReactJS' },
{ key: 'React Native' },
{ key: 'VueJS' },
{ key: 'EmberJS' },
{ key: 'NodeJS' },
{ key: 'ExpressJS' },
{ key: 'BackboneJS' },
{ key: 'ExtJS' }
]
}
}
Engender a function designated as ItemSeparator. Utilizing this method we are engendering the FlatList each item separator – divider line
ItemSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "purple",
}}
/>
);
}
Engender a Root View in render’s return block.
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.ListItems}
ItemSeparatorComponent={this.ItemSeparator}
renderItem={({ item }) => <Text style={styles.item}
onPress={this.Item.bind(this, item.key)} > {item.key} </Text>}
/>
</View>
);
}
}
Engender Style
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
flex: 2,
margin: 12
},
item: {
padding: 12,
fontSize: 20,
height: 47,
},
});
Complete source code for App.js File
import React from 'react';
import { StyleSheet, FlatList, Text, View, Alert } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
ListItems: [
{ key: 'Javacsript' },
{ key: 'jQuery' },
{ key: 'Angular' },
{ key: 'ReactJS' },
{ key: 'React Native' },
{ key: 'VueJS' },
{ key: 'EmberJS' },
{ key: 'NodeJS' },
{ key: 'ExpressJS' },
{ key: 'BackboneJS' },
{ key: 'ExtJS' }
]
}
}
ItemSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "purple",
}}
/>
);
}
Item(item) {
Alert.alert(item);
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.ListItems}
ItemSeparatorComponent={this.ItemSeparator}
renderItem={({ item }) => <Text style={styles.item}
onPress={this.Item.bind(this, item.key)} > {item.key} </Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
flex: 2,
margin: 12
},
item: {
padding: 12,
fontSize: 20,
height: 47,
},
});
Run
sibinmuhammed@ladmin-H310M-S2:~$ react-native start
sibinmuhammed@ladmin-H310M-S2:~/knf-reactnative/KnowledgeFactoryDemo$ react-native run-android