In this tutorial we would going to learn about parsing JSON data in react native application using Fetch API networking library. Fetch API is one of the common API’s used by react native developers. So using this API we would retrieve the complete JSON object from MySQL database server. The MySQL database data is convert into JSON fromat using PHP. So let’s get started
Contents in this project JSON Parsing ListView :
1. Create Database + Table on your online hosting server or local server :
Create a fresh table inside your database named as FruitsNameListTable . The table has two columns id and fruit_name.
2. Insert Records into Table :
Next step is to insert some records into your table for example i am creating table to store different type of fruit names. Below is the screenshot of my table after inserting records.
3. Create PHP file code to retrieve data from MySQL database and convert into JSON.
Now create Two PHP files First one is DBConfig.php and second is FruitsList.php.
DBConfig.php :- This file contains your hosting server configuration like server host name, database name, database username and database password.
FruitsList.php :- This file fetch the MySQL records from table and convert them into JSON than ECHO them on screen, so they can be accessible.
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();
?>
|
Output of JSON after running the URL should look like this :
4. Start a fresh React Native project. If you don’t know how then read my this tutorial.
5. Add
AppRegistry ,
StyleSheet ,
ActivityIndicator ,
ListView ,
Text ,
View ,
Alert component in import block.
1
|
import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from ‘react-native’;
|
6. Create constructor in your class with props and set this.state isLoading: true.
isLoading: true tells us whether our JSON data is loading from server or not so we can hide the Activity indicator.
1
2
3
4
5
6
|
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
|
7. Create a function to display the JSON listview selected item. The function name is GetItem with fruit_name parameter, than the function name should look this this : GetItem (fruit_name) .
This function is used to show the selected item from ListView in alert message.
1
2
3
4
5
|
GetItem (fruit_name) {
Alert.alert(fruit_name);
}
|
8. Create
componentDidMount() method. This is a inbuilt method.
1
2
3
4
|
componentDidMount() {
}
|
9. Create Fetch API network request in
componentDidMount() method.
Using Fetch method first we can pass our HTTP URL from which the JSON is coming. Then using response object we have hold the response coming from server. Now fill the JSON object items to ListView rows one by one.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
componentDidMount() {
return fetch(‘https://reactnativecode.000webhostapp.com/FruitsList.php’)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
|
10. Create
ListViewItemSeparator method.
Using this method we would show a simple item separator line between ListView items.
1
2
3
4
5
6
7
8
9
10
11
|
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: “100%”,
backgroundColor: “#000”,
}}
/>
);
}
|
11. Inside the
render() block put a if condition checking on this.state.isLoading and if the this.state.isLoading is true then show the
<ActivityIndicator /> .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
);
}
}
|
12. Create custom css class named as MainContainer and rowViewContainer just above the AppRegistry.registerComponent line.
MainContainer : is for complete layout screen.
rowViewContainer : is to modify each ListView element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
const styles = StyleSheet.create({
MainContainer :{
// Setting up View inside content in Vertically center.
justifyContent: ‘center’,
flex:1,
margin: 10
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
}
});
|
13. Add View as parent view in render’s return block and Call the MainContainer class into View.
1
2
3
4
5
6
7
8
|
return (
<View style={styles.MainContainer}>
</View>
);
|
14. Add
ListView component in View.
dataSource : Adding the JSON data into ListView.
renderSeparator : Display a border between items using
ListViewItemSeparator() .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.GetItem.bind(this, rowData.fruit_name)} >{rowData.fruit_name}</Text>}
/>
</View>
);
|
15. 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
|
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from ‘react-native’;
class Myproject extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
GetItem (fruit_name) {
Alert.alert(fruit_name);
}
componentDidMount() {
return fetch(‘https://reactnativecode.000webhostapp.com/FruitsList.php’)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: “100%”,
backgroundColor: “#000”,
}}
/>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.GetItem.bind(this, rowData.fruit_name)} >{rowData.fruit_name}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
// Setting up View inside content in Vertically center.
justifyContent: ‘center’,
flex:1,
margin: 10
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
}
});
AppRegistry.registerComponent(‘Myproject’, () => Myproject);
|
Screenshots: