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 :
How to fetch multiple API’s in COmponentDidMount() function. ?
Please respond.
Hitesh Just create multiple functions with API’s and call all that functions inside the ComponentDidMount() function.
error in( this.state.dataSource.map) can u help me
Hassan the error is showing our code or your edited code ?
help plz , i am having the same error!
TypeError: undefined is not an object (evaluation’this.state.dataSource.map’)
Hi admin,
I am working on autocomplete input in react native. It would be helpful if you post a tutorial on that ?
Sorry Hitesh i have not tried yet the autocompleteTextInput.
how to set width of Picker.item ?
Tony only iOS support Picker item style. You can apply style on Picker item but it will only works in iOS devices.
Hi admin, when i try your code it error like this “undefined is not a function(evaluating ‘this.state.dataSource.map’)” what is going on and how to fix it.
Krissana please check your DBConfig.php file that you have configured correctly .
Oh, It’s work now. Thank you very much.
Welcome Krissana 🙂 .
This is wonderful, thank you so much for this tutorial.
Can you help me take this one step further?
I would like to store the data, used to populate the picker, in async storage to be used offline instead of the error that comes up when not on the internet.
Aubrey you can use Realm instead of Async Storage to store data locally. Read my this tutorial this would help you : https://reactnativecode.com/installing-realm-mobile-database-windows-mac/
This is very cool. how would you take the mysql and store it in a new realm then use it in a picker?
Aubrey i will soon publish a new tutorial regarding to your query 🙂 .
Hello
You could help me perform the function that inserts that value of the picker into another table in the database.
please
thank you very much
Luis just read our this tutorial to save the selected value in mysql database : https://reactnativecode.com/react-native-insert-text-input-data-to-mysql-server/
That would be wonderful! When can I expect this gem?
Aubrey this will take some time i would say 2 to 3 weeks maybe 🙂 .
Is there anyway I can get a slimmed down version or a snippet for the integration as this is a project I’m working now? Or point me in the right direction. I would realllly appreciate it ????
Aubrey you can read my current tutorial on realm now what you have to do is at the inserting point just store the JSON data into realm using looping.
Hi
Sorry to disturb you again
I use like fetch : https://192.168.0.40/testbaby/FruitsList.php
If i put this link on the web browser I have the JSON
But in the application I have “Request Network Failed”
http://192.168.0.40/testbaby/FruitsList.php Sorry
Avi you are connected to internet while testing this code ?
Fetch() is work over internet connection, why you are using the local system for testing you can use free hosting likes 000webhost to make your free online website and test your code like we did.
Goodnight
Thank you very much for sharing your knowledge.
You could explain how I do to save the selected value in another table in my database.
Beforehand thank you very much
Luis just read our this tutorial to save the selected value in mysql database : https://reactnativecode.com/react-native-insert-text-input-data-to-mysql-server/
Hello
You could help me perform the function that inserts that value of the picker into another table in the database.
please
thank you very much
Hi, i’m facing problem to get Dynamic picker value. Here is my code
….
let LocationDropDown = this.state.results.Locations.map((Location) => {
return (
);
});
…
— Static Code per line working fine
—-
I think due to Quotation “” it not working.
Would please help me how can i add Quotation with {Carly bracket}
Expectation
Or what would my coding way….
Remark: I’m new in React-Native
Khairul please explain your question more briefly .
If there is only one row of data in Data in my SQL, your code doesn’t work. If more than a single row your code works fine.
Thanks
Harish the code is working properly i have checked it but i will check it again .
dear when i merge the code with my code itz takes lots of time for loading atround 15min then code is not working.import React, { Component } from ‘react’;
import { StyleSheet, TouchableOpacity,AppRegistry,onButtonPress,Field, onPress,
ScrollView, Text,Picker,Item, TextInput,Alert,View,Button,Image,KeyboardAvoidingView,keyboard,ActivityIndicator} from ‘react-native’;
import ImageViewer from ‘react-native-image-zoom-viewer’;
import Modal from ‘react-native-modal’;
import Permissions from ‘react-native-permissions’;
import AppHeader from’../Components/AppHeader’;
import GLOBALS from ‘../Components/Globals’;
import { KeyboardAwareScrollView } from ‘react-native-keyboard-aware-scroll-view’;
export default class Bankupdation extends React.Component {
// let PickerItem = Picker.Item;
constructor(props) {
super(props);
this.state = {
your_name:”,
Branch_Name:”,
Account_Number:”,
Re_Enter_Account_Number:”,
IFSC_Code:”,
dropdownData: []
// PickerValueHolder
};
}
loadData(item) {
return item.options.map(user => (
))
}
onClickDropdown(value,index){
let selectValue = this.state.selectedDropDownValue;
selectValue[index] = value;
this.setState({
selectedDropDownValue: selectValue
});
}
onClickDropdown(data, index, item){
// save each items selected data with their id
this.setState((prevState) => {
const value = Object.assign({}, prevState.selectedDropDownValue, { [item.id]: data});
return { selectedDropDownValue: value};
});
}
// bank() {
// fetch(‘https://api.earnwealth.in/api_bank_name.php’)
// then((response) => response.json())
// .then((responseJson) => {
// // var count = Object.keys(responseJson.Obj).length;
// let drop_down_data = [];
// for(var i=0;i {
// console.error(error);
// });
// componentDidMount() {
// fetch(‘url’,
// .then((response) => response.json())
// .then((responseJson) => {
// var count = Object.keys(responseJson.message.Obj).length;
// // We need to treat this.state as if it were immutable.
// // So first create the data array (tempDataArray)
// var tempDataArray = [];
// for(var i=0;i {
// console.error(error);
// });
// }
//
// return fetch(‘https://api.earnwealth.in/api_bank_name.php’)
// .then((response) => response.json())
// .then((responseJson) => {
// this.setState({
// isLoading: false,
// dataSource: responseJson
// }, function() {
// console.log(this.state.PickerValueHolder);
// });
// })
// .catch((error) => {
// console.error(error);
// });
// }
//
onbankdetail()
{
const your_name = this.state.your_name;
const Bank_Name = this.state.PickerValueHolder;
const Branch_Name = this.state.Branch_Name;
const Account_Number = this.state.Account_Number;
const Re_Enter_Account_Number=this.state.Re_Enter_Account_Number;
const IFSC_Code=this.state.IFSC_Code;
let {Error,Error1,Error2,Error3,Error4,Error5} = this.state;
if(Re_Enter_Account_Number !== Account_Number){
Alert.alert(“your account number is not matched “)
}
else if (your_name.length == 0 )
{
this.setState(() => ({Error: ‘You must enter your name’}));
}else if (Bank_Name.length !== 0)
{
this.setState(() => ({Error1: ‘You must enter bank name’}));
}
else if (Branch_Name.length !== 0)
{
this.setState(() => ({Error2: ‘You must enter branch name’}));
}
else if (Account_Number.length !== 16)
{
this.setState(() => ({Error3: ‘You must enter account number’}));
}
else if (Re_Enter_Account_Number !== 16)
{
this.setState(() => ({Error4: ‘You must enter re-enter account number’}));
}
else if (IFSC_Code !== 12)
{
this.setState(() => ({Error5: ‘You must enter IFSC code’}));
}
else{
var bodyFormData = new FormData();
bodyFormData.append(‘rp_code’,GLOBALS.RP_CODE);
bodyFormData.append(‘acc_holder_name’,your_name);
bodyFormData.append(‘bank_name’,Bank_Name);
bodyFormData.append(‘branch_name’,Branch_Name);
bodyFormData.append(‘acc_number’,Account_Number);
bodyFormData.append(‘ifsc_code’,IFSC_Code);
bodyFormData.append(‘cancel_cheque’,’Appcancelledcheque’);
fetch(‘https://api.earnwealth.in/api_rp_account_details.php’,
{
method: ‘POST’,
body:bodyFormData
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
Alert.alert(” RP Registration done successful”);
this.props.navigation.navigate(‘home’);
})
.catch(error => {
console.error(error);
});
}
}
render() {
// if (this.state.isLoading) {
// return (
//
//
//
// );
// }
return (
Bank Detail
this.setState({your_name})}
underlineColorAndroid=’transparent’ placeholder=’Your Name(As per Bank Account)’ />
{!!this.state.Error && ({this.state.Error})}
this.onClickDropdown(itemValue, itemIndex, item)}
>
{this.loadData(item)}
this.setState({Bank_Name})}
underlineColorAndroid=’transparent’ placeholder=’Bank Name’ />
{!!this.state.Error && ({this.state.Error1})}
this.setState({Branch_Name})}
underlineColorAndroid=’transparent’ placeholder=’Branch Name’ />
{!!this.state.Error && ({this.state.Error2})}
this.setState({Account_Number})}
underlineColorAndroid=’transparent’ placeholder=’Account Number’ />
{!!this.state.Error && ({this.state.Error3})}
this.setState({Re_Enter_Account_Number})}
underlineColorAndroid=’transparent’ placeholder=’Re Enter Account Number’ />
{!!this.state.Error && ({this.state.Error4})}
this.setState({IFSC_Code})}
underlineColorAndroid=’transparent’ placeholder=’IFSC Code’ />
{!!this.state.Error && ({this.state.Error5})}
Submit
);
}
}
const styles = StyleSheet.create({
keyboardAvoding: {
flex: 1,
backgroundColor: ‘rgba(200, 200, 230, 0.3)’,
},
keyboardAvoidContainer: {
flex: 1,
backgroundColor: ‘white’
},
container: {
backgroundColor: ‘#fff’,
},
input1:{
height:40,
width:’90%’,
borderRadius: 4,
borderWidth: 0.5,
borderColor: ‘#d6d7da’,
// textAlign: ‘center’,
marginTop:15,
marginLeft:10,
backgroundColor: ‘#ffffff’,
marginBottom: 10,
padding: 10,
color: ‘black’
},
button: {
color: ‘white’,
borderRadius: 5,
marginBottom: 20,
backgroundColor: ‘#ec1f24′,
paddingVertical: 10,
width:’50%’,
height:40,
textAlign: ‘center’,
marginLeft:’25%’,
marginTop:20,
},
image: {
width: 80,
height: 80,
},
MainContainer: {
height:40,
width:’90%’,
borderRadius: 4,
borderWidth: 0.5,
borderColor: ‘#d6d7da’,
textAlign: ‘center’,
marginTop:15,
marginLeft:10,
backgroundColor: ‘#ffffff’,
marginBottom: 10,
// padding: 10,
color: ‘black’
},
rowcontainer:{
flexDirection:’row’,
alignItems: ‘center’,
justifyContent: ‘center’,
color: ‘black’
},
});
code is hear and can you plese provied me your gmail account
so you can help me .
Pooja mail your code on [email protected] .
Above code show Cannot read property ‘map’ of undefined error in console.
Harmis try to uninstall the app from simulator and than try again.
Hola harmis , haz podido solucionar tu duda ? ,
tengo el mismo error en this.state.dataSource.map
hi admin, can you show to me how to make double picker from different table data (mysql). I have try it but the second picker does not showing.
You want to choose picker from different tables on same page.
yes. let say i have 2 table related which is hospital and discipline. The first picker is hospital and second picker is discipline
Thank you very much Admin. This has been beyond helpful. I’m new to react native and your tutorials are how I usually get hands-on practice. Moving forward like bil says, I would also like to know how to do something similar with related mysql tables, a first picker and a second on the same page.
Thanks for comment Kofi, I will currently working on some similar tutorials and soon publish them one by one.
how we can fetched data into picker insert into another relational table
Abhaysakpal we need to select the selection value then we can sent it anywhere .
fetch data from API and show in SwipeFlatList
Please explain your query more briefly .
I think you should create a state dataSource before storing any data in it.
Thanks for your suggestion Parth :).
Can you please show how to create state dataSource?
I am stuck with a similar kind of problem.
Parth read my this tutorial in this tutorial i have make static data source using state : https://reactnativecode.com/add-sticky-header-to-listview/ .
how to implement dynamic dependent picker in react native
dynamic dependent picker ? Means .
Hi Admin,
Awesome.Thank you so much..Wasted a lot of time for this..Finally Worked……Great
hai sir i have sent you mail regarding issue in state.datasource.map….
God bless you.God bless your soul.You saved my life 🙂
Thanks Shahbaz 🙂 .
sir are u still active on this site ?
i need your help
Dhiraj, lately i am in a family situation so i was unable to active on site, But from tomorrow i will be regular on this site.