FlatList is the advance version of ListView with more user handy features like it is fully cross platform and dose support both Android and iOS mobile phone devices. It has also an optional horizontal mode which is used to display the FlatList in horizontal mode. So in this tutorial we would going to create a simple FlatList using JSON Parsing Data which is coming straight from our online hosting server android and iOS tutorial. The JSON data is already stored into a MySQL database. So let’s get started .
Contents in this project Create FlatList using JSON Parsing Data :
1. Create MySQL database on your local or online hosting server.
2. Inside that MySQL database create a fresh table named as FruitsNameListTable with 2 columns first one is id second is fruit_name . Set id as primary key in MySQL table. Now insert some records inside your MySQL database table like i did in below screenshot.
3. Create PHP Script to Convert MySQL database data into JSON form :
Create 2 PHP files 1st one is DBConfig.php and 2nd is FruitsList.php.
FruitsList.php : This file would get all the Records from MySQL db table and ECHO (Print) them on screen into JSON data form.
DBConfig.php : This file holds all the important information like Server Host Name, Database Name, Database Password and Database User Name.
Code for DBConfig.php file :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
//Define your host here.
$HostName = “localhost”;
//Define your database name here.
$DatabaseName = “id2070055_reactnativedb”;
//Define your database username here.
$HostUser = “id2070055_reactnativedb_user”;
//Define your database password here.
$HostPass = “1234567890”;
?>
|
Code for FruitsList.php file :
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
|
<?php
include ‘DBConfig.php’;
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}
$sql = “SELECT * FROM FruitsNameListTable”;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo “No Results Found.”;
}
echo $json;
$conn->close();
?>
|
Screenshot of JSON data after uploading and running FruitsList.php file into web browser :
4. Start a fresh React Native project. If you don’t know how then read my this tutorial.
5. Import AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform in import block.
1
2
3
|
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from ‘react-native’;
|
6. Create constructor with props parameter. Define a new state variable inside the constructor named as isLoading and set its value as True . This variable is used to show and hide the ActivityIndicator after parsing the JSON data into FlatList.
1
2
3
4
5
6
7
8
9
|
constructor(props)
{
super(props);
this.state = {
isLoading: true
}
}
|
7. Create componentDidMount() method after constructor. This is a inbuilt function and automatically called on App start time. Inside the componentDidMount() function define the fetch web API code. The JSON would be parse using fetch API.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
componentDidMount() {
return fetch(‘https://reactnativecode.000webhostapp.com/FruitsList.php’)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
|
8. Create FlatListItemSeparator() function after componentDidMount() function. This function would Create a custom FlatList item divider line between each FlatList item.
1
2
3
4
5
6
7
8
9
10
11
|
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: “100%”,
backgroundColor: “#607D8B”,
}}
/>
);
}
|
9. Create GetFlatListItem() function . This function is used to PRINT the selected FlatList item value using Alert message on app screen.
1
2
3
4
5
|
GetFlatListItem (fruit_name) {
Alert.alert(fruit_name);
}
|
10. Set a if condition inside the render block. Using this if condition we would check the isLoading state’s value and show and hide the ActivityIndicator .
1
2
3
4
5
6
7
8
9
10
11
12
13
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return ( ) ;
}
|
11. Now create FlatList component inside the render’s return block inside a Parent View.
data : Set the dataSource created in componentDidMount() method inside the fetch API.
ItemSeparatorComponent : Call the FlatListItemSeparator() function.
renderItem : render the FlatList item using Text component.
onPress : Call the GetFlatListItem function to show the clicked item value.
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
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <Text style={styles.FlatListItemStyle} onPress={this.GetFlatListItem.bind(this, item.fruit_name)} > {item.fruit_name} </Text>}
keyExtractor={(item, index) => index}
/>
</View>
);
}
|
12. Create Custom Style sheet class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
const styles = StyleSheet.create({
MainContainer :{
justifyContent: ‘center’,
flex:1,
margin: 10,
paddingTop: (Platform.OS === ‘ios’) ? 20 : 0,
},
FlatListItemStyle: {
padding: 10,
fontSize: 18,
height: 44,
},
});
|
13. Complete source code for index.android.js / index.ios.js file :
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from ‘react-native’;
class Project extends Component {
constructor(props)
{
super(props);
this.state = {
isLoading: true
}
}
componentDidMount() {
return fetch(‘https://reactnativecode.000webhostapp.com/FruitsList.php’)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: “100%”,
backgroundColor: “#607D8B”,
}}
/>
);
}
GetFlatListItem (fruit_name) {
Alert.alert(fruit_name);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <Text style={styles.FlatListItemStyle} onPress={this.GetFlatListItem.bind(this, item.fruit_name)} > {item.fruit_name} </Text>}
keyExtractor={(item, index) => index}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: ‘center’,
flex:1,
margin: 10,
paddingTop: (Platform.OS === ‘ios’) ? 20 : 0,
},
FlatListItemStyle: {
padding: 10,
fontSize: 18,
height: 44,
},
});
AppRegistry.registerComponent(‘Project’, () => Project);
|
Screenshot of Application in iOS mobile phone device :
Screenshot of Application in Android mobile phone device :