In our previous tutorial Simple Picker in React Native we have created Picker using static elements but this tutorial is the advanced part of that tutorial. Because in this tutorial we would going Create Picker Spinner Using Dynamic JSON Data coming from online MySQL database server in Android iOS react native app. All the Picker items is stored in MySQL database and we would use the PHP Script code for convert MySQL data into JSON form. We would also retrieve the Picker-Drop Down-Spinner selected value on button click. So let’s get started .
Contents in this project Create Picker Spinner Using Dynamic JSON MySQL Data in React Native :
1. Create a fresh MySQL database on your Online or Local server.
2. Create a Table in your MySQL database named as FruitsNameListTable with 2 columns id and fruit_name. Now we would add some fruit names inside table. Below is the screenshot of MySQL table after adding Fruit names.
3. Create PHP code to convert MySQL database data into JSON. We would parse this converted JSON in our react native app :
Create 2 PHP files named as DBConfig.php and FruitsList.php.
DBConfig.php : This file holds all the database hostname, username, password and database name. Modify this file according to your server configuration.
FruitsList.php : This file would modify the FruitsNameListTable list and convert them into JSON format.
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 after running FruitsList.php in web browser :
4. Start a new react native project or open your existing project in which you want to add JSON data Picker.
5. Import AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button and Alert component in your project.
1
2
3
|
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from ‘react-native’;
|
6. Create constructor() in your class. Now we would make 2 States named as isLoading and PickerValueHolder. isLoading state is used to show and hide the ActivityIndicator after done parsing JSON. PickerValueHolder State is used to hold the Picker selected element value.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
constructor(props)
{
super(props);
this.state = {
isLoading: true,
PickerValueHolder : ”
}
}
|
7. Create componentDidMount() method in your class. This method is a inbuilt method and called automatically on application starts time. Now we would create the Fetch() Web API to parse JSON and we would store the parsed JSON inside dataSource state using setState({}) method and also set the isLoading state value False so after done loading JSON it will hide the ActivityIndicator.
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 a function named as GetPickerSelectedItemValue(). This function is used show the Picker selected item using Alert.
1
2
3
4
5
|
GetPickerSelectedItemValue=()=>{
Alert.alert(this.state.PickerValueHolder);
}
|
9. Now we would set a IF condition in render’s block and using the isLoading state we would show and hide the ActivityIndicator. If the isLoading state is true then it will show the ActivityIndicator and if the isLoading state value is false then it will hide the ActivityIndicator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
);
}
|
10. Create a Root View in render’s return block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
</View>
);
}
|
11. Now we write the Picker component in Root View. We would also add a Button in this view and call the GetPickerSelectedItemValue() function on button onPress event.
selectedValue : Set the selected value in Picker.
onValueChange : Store the Selected value in State.
Picker.Item : Is used to add the item inside Picker.
label : Show the label name in picker.
value : add the value in Picker.
Note : We would populate the Picker items from dataSource state using .MAP function.
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
|
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<Picker
selectedValue={this.state.PickerValueHolder}
onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >
{ this.state.dataSource.map((item, key)=>(
<Picker.Item label={item.fruit_name} value={item.fruit_name} key={key} />)
)}
</Picker>
</View>
);
}
|
12. Create Style for Root View.
1
2
3
4
5
6
7
8
9
10
|
const styles = StyleSheet.create({
MainContainer :{
justifyContent: ‘center’,
flex:1,
margin: 10
}
});
|
13. Complete source code for App.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
|
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from ‘react-native’;
export default class Project extends Component {
constructor(props)
{
super(props);
this.state = {
isLoading: true,
PickerValueHolder : ”
}
}
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);
});
}
GetPickerSelectedItemValue=()=>{
Alert.alert(this.state.PickerValueHolder);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<Picker
selectedValue={this.state.PickerValueHolder}
onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >
{ this.state.dataSource.map((item, key)=>(
<Picker.Item label={item.fruit_name} value={item.fruit_name} key={key} />)
)}
</Picker>
<Button title=“Click Here To Get Picker Selected Item Value” onPress={ this.GetPickerSelectedItemValue } />
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: ‘center’,
flex:1,
margin: 10
}
});
|
Screenshot in Android device :