React Native Create Picker Spinner Using Dynamic JSON MySQL Data

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 :

Code for FruitsList.php file :

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.

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.

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.

8. Create a function named as GetPickerSelectedItemValue(). This function is used show the Picker selected item using Alert.

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.

10. Create a Root View in render’s return block.

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.

12. Create Style for Root View.

13. Complete source code for App.js File :

Screenshot in Android device :

Create Picker Spinner Using Dynamic JSON Picker Spinner Screenshot in iOS device :

59 Comments

  1. How to fetch multiple API’s in COmponentDidMount() function. ?
    Please respond.

  2. Hi admin,
    I am working on autocomplete input in react native. It would be helpful if you post a tutorial on that ?

  3. how to set width of Picker.item ?

  4. Krissana Leawchavalit

    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.

  5. 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.

  6. This is very cool. how would you take the mysql and store it in a new realm then use it in a picker?

  7. That would be wonderful! When can I expect this gem?

  8. 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.

  9. 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”

  10. 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

  11. 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

  12. 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

  13. 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

  14. 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 .

  15. Above code show Cannot read property ‘map’ of undefined error in console.

  16. 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.

  17. yes. let say i have 2 table related which is hospital and discipline. The first picker is hospital and second picker is discipline

  18. 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.

  19. how we can fetched data into picker insert into another relational table

  20. fetch data from API and show in SwipeFlatList

  21. Parth Shrivastav

    I think you should create a state dataSource before storing any data in it.

  22. Parth Shrivastav

    Can you please show how to create state dataSource?
    I am stuck with a similar kind of problem.

  23. how to implement dynamic dependent picker in react native

  24. Hi Admin,
    Awesome.Thank you so much..Wasted a lot of time for this..Finally Worked……Great

  25. hai sir i have sent you mail regarding issue in state.datasource.map….

  26. God bless you.God bless your soul.You saved my life 🙂

  27. sir are u still active on this site ?
    i need your help

Leave a Reply

Your email address will not be published. Required fields are marked *