Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS - How do I bind json data to a dropdown list

Tags:

json

reactjs

I have a react JS file and I'm attempting to bind data to a dropdown list. The data is stored in the following testing API/json file: https://api.myjson.com/bins/okuxu ...I want to start by binding the client name to it's respective dropdown list.

Sample json data:

[
    {
        "abc_buildingid": "11111112-64c2-5bd8-8b72-e92568694c76",
        "abc_energyprogramid": "5d84ef73-9b9a-475f-84e2-f307ad897df7",
        "siteName": "Construction One",
        "sampleCalibration": false,
        "clientName": "Client-1",
        "segmentName": "John Doe ES New Silver 4-7-2017-04-30-2018~25313~John Doe ES JDU Area Calibration~47851~Mod",
        "cfmRateFactor": 50
    }
]

...this is my code:

import React, { Component } from 'react';

class Ast extends Component {

   constructor(){
       super();
       this.state = {
           data: [],
       };
   } //end constructor

   bindDropDowns() {
       var clientName = document.getElementById('clientName').value

       for(var i=0; i < this.state.data.length; i++) {
        var clientName = this.state.data[i].clientName;
       }
   }

   componentWillMount() {
    fetch('https://api.myjson.com/bins/okuxu', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json',
        },
        /*body: JSON.stringify({
            username: '{userName}',
            password: '{password}'
        })*/
    }) /*end fetch */
    .then(results => results.json()) 
    .then(data => this.setState({ data: data })   
)

} //end life cycle

    render() {
        console.log(this.state.data);
        return (
            <div>


                <form>
                    <div>

                        <h2>Memeber Selection:</h2>

                        <div>

                            <div>
                                <select className="custom-select" id="clientName" onSelect="bindDropDowns()">
                                <option selected>Client</option>
                                </select>     
                            </div><br />

                            <div>
                                <select className="custom-select" id="siteName">
                                <option selected>Site Building Name</option>
                                </select>
                            </div><br />
                            <div>
                                <select className="custom-select" id="segmentName">
                                <option selected>Segments</option>
                                </select>
                            </div><br />
                           <div>
                                <label for="example-text-input">Modify CFM Rate Factor:</label>
                                <input class="form-control" type="textbox"  id="cfmRateFactor" value="10" />
                            </div><br />
                                <div>
                                    <button type="submit" className="btn btn-primary">Submit</button>
                                </div>
                            </div>
                    </div>
                    </form>
            </div>


        );
      }
}

export default Ast

I confirmed via the console that "this.state.data" contains all the information from the json file, so now I'm attempting to bind the client names to a dropdown list. Could I please get some guidance as to what I'm doing wrong?

like image 231
user1724708 Avatar asked May 06 '18 02:05

user1724708


People also ask

How do you populate a dropdown with JSON data in React?

If you want to hold your data in a seperate json file; You can declare the data like this. You import this file in the component where your dropdown list is in like this. import {Cities} from "../../assets/data/cities.

How to create a dropdown list in react?

To create a dropdown list, you can use a third-party library such as react-select, or you can create a custom dropdown menu component in React. If you are more comfortable in watching a video that explains about How to Create React Dropdown Select, then you should watch this video tutorial.

How to get data from JSON placeholder in react select?

For the data, we will be using API from JSON placeholder Open your project directory and install react-select and axios. 2. Now open your app.js file. We will be using class component so first, create a constructor and initialize some state. 3.

How do I import JSON data into React React?

React allows using named imports, and we can leverage that to load JSON data. So go ahead and add this import in your src/Stocks.js file. The next task is to iterate over the stockData array imported from the data.js file. Inside your <Stocks> component, add the logic to go over every element from the stockData array.

How does the dropdownlist work?

The DropDownList loads the data either from local data sources or remote data services using the dataSource property. It supports the data type of array or DataManager.


3 Answers

In React, you use a declarative approach instead of DOM manipulation:

<div>
  {['clientName', 'siteName', 'segmentName'].map(key => (
    <select key={key}>
      {this.state.data.map(({ [key]: value }) => <option key={value}>{value}</option>)}
    </select>
  ))}
</div>

This generates the 3 dropdowns with the options populated.

like image 144
Roy Wang Avatar answered Nov 14 '22 21:11

Roy Wang


In this.state define the json -

CityNames : {
                CityName : 
                    [
                        {CityKey : 1,CityDescription: 'abc'},
                        {CityKey : 2,CityDescription: 'xyz'}
                    ]

        }

Here is the code for Drop Down List

<select className="form-control">
          <option>---select---</option>
            {
            this.state.CityNames &&
            this.state.CityNames.CityName.map((h, i) => 
            (<option key={i} value={h.CityName}>{h.CityDescription}</option>))
            }
</select>
like image 31
MERLIN THOMAS Avatar answered Nov 14 '22 23:11

MERLIN THOMAS


To populate data into the dropdown list

import your .json file

<select>
    <option> Select User</option>
      {
       data.map((result)=>(<option title={result.Id}>{result.title}</option>))
      }
</select>
like image 37
Munaf_root Avatar answered Nov 14 '22 21:11

Munaf_root