8

I'm currently trying to take some JSON data that I've received from an API and put that into a dropdown in a very simple React application.

This is my DropDown component thus far:

import React from 'react';

var values;

fetch('http://localhost:8080/values')
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        values = json;
        console.log(values);
    });

class DropDown extends React.Component {
    render(){
        return <div className="drop-down">
            <p>I would like to render a dropdown here from the values object</p>
            </div>;
    }
}

export default DropDown;

Any my JSON looks like this:

{  
   "values":[  
      {  
         "id":0,
         "name":"Jeff"
      },
      {  
         "id":1,
         "name":"Joe"
      },
      {  
         "id":2,
         "name":"John"
      },
      {  
         "id":3,
         "name":"Billy"
      },
      {  
         "id":4,
         "name":"Horace"
      },
      {  
         "id":5,
         "name":"Greg"
      }
   ]
}

I'd like the dropdown options to correspond to the 'name' of each element, and the 'id' to be used as an element identifier when an event is triggered by selecting an option. Any advice on getting this data into a dropdown which responds to user input would be greatly appreciated.

3
  • 1
    You can iterate over values of the JSON with .map to build your <select> and <options> and use onChange for <select>. Have you tried this? Commented Feb 28, 2018 at 16:17
  • Not yet. Could you give me a quick example of how it's used? Commented Feb 28, 2018 at 16:24
  • As in the below answer, make sure to make an api call in componentdidmount which is one of the best method to make API calls Commented Feb 28, 2018 at 16:33

4 Answers 4

4

You could do something like this:

import React from 'react';

var values;

class DropDown extends React.Component {

    constructor(){
        super();
        this.state = {
            options: []
        }  
    }

    componentDidMount(){
        this.fetchOptions()
    }

    fetchOptions(){
        fetch('http://localhost:8080/values')
            .then((res) => {
                return res.json();
            }).then((json) => {
                values = json;
                this.setState({options: values.values})
                console.log(values);
            });
    }
    render(){
        return <div className="drop-down">
            <select>
                { this.state.options.map((option, key) => <option key={key} >{option}</option>) }
            </select>
            </div>;
    }
}

export default DropDown;

Basically you are initializing state and setting options to null.

You are then fetching your options when the component mounts in the browser. These values are set to your state with this.setState().

Note: It is important to make any API calls in componentDidMount() and not componentWillMount(). If you call it in componentWillMount() the request will be made twice.

Then you render these options by mapping them in your render function

Sign up to request clarification or add additional context in comments.

17 Comments

Thanks Stretch. I'm getting some errors when I run this: Module build failed: SyntaxError: Unexpected token (7:10) 5 | class DropDown extends React.Component { 6 | > 7 | state = { | ^ 8 | options: null 9 | } 10 |
@HomerPlata I have updated to use a constructor instead. Try updating your code to match mine by setting the state inside the constructor function
@HomerPlata just updated again but best to initialize options as an empty array
Now I'm seeing: Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined.
Ah yes, you need to use lambda functions instead so that the context of this refers to the class and is not scoped to the function you are calling this in. @HomerPlata have updated the example for you
|
4

Call the API in componentDidMount lifecycle function of your React component and then save the response in state and then render the Select dropdown

import React from 'react';

class DropDown extends React.Component {
    state = {
        values: []
    }
    componentDidMount() {
       fetch('http://localhost:8080/values')
        .then(function(res) {
            return res.json();
        }).then((json)=> {
            this.setState({
               values: json
            })
        });
    }
    render(){
        return <div className="drop-down">
            <p>I would like to render a dropdown here from the values object</p>
              <select>{
                 this.state.values.map((obj) => {
                     return <option value={obj.id}>{obj.name}</option>
                 })
              }</select>
            </div>;
    }
}

export default DropDown;

Comments

1

JSON FILE: terrifcalculatordata.json
[
    {
      "id": 1,
      "name": "Vigo",
    },
    {
      "id": 2,
      "name": "Mercedes",
    },
    {
        "id": 3,
        "name": "Lexus",
      },
      {
        "id": 4,
        "name": "Buggati",
      },
]

CODE: 
1st import json file on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

2nd in render method type this code: 

                      <Form>
                            <FormGroup>
                              <Input
                              type="select"
                              onChange = {this.changeCarmodel}
                              value={this.state.changeCar}
                              >
                              {calculatorData.map((caldata, index) =>
                                <option 
                                key={index}
                                value= {caldata.id}
                                > {caldata.name} </option>
                              )}
                              </Input>
                            </FormGroup>
                         </Form>

Comments

0

How to render JSON response as dropdown list in React.

export default class ExpenseNew extends Component {
    constructor(){
        super();
        this.state={
            PickerSelectedVal : '',
            accountnameMain:[],
        }
    }
     componentDidMount(){
         var account_nam=[]
                fetch('your Url', {
                    method: 'GET',
                    headers: { 'Authorization': 'Bearer ' + your token }
                })
                    .then((response) => response.json())
                    .then((customerselect) => {
                        // alert(JSON.stringify(customerselect)) 
                        global.customerdata = JSON.stringify(customerselect)
                        var customername = JSON.parse(customerdata);
                        //alert(JSON.stringify(customername));
                        for (i = 0; i < customername.cus_data.length; i++) {
                            var dataa = customername.cus_data[i]["account_name"];  
                            account_nam.push(dataa)
                        }
                        this.setState({accountnameMain:account_nam});
                    })
                    .done();
    }
                    render() {
                          return (
                               <Picker
                                selectedValue={this.state.PickerSelectedVal}
                                placeholder="Select your customer"
                                mode="dropdown"
                                iosIcon={<Icon name="arrow-down" />}
                                onValueChange={(itemValue, itemIndex) => this.setState({PickerSelectedVal: itemValue})} >

                                {this.state.accountnameMain.map((item, key)=>(
                                    <Picker.Item label={item} value={item} key={key}/>)
                                )}

                            </Picker>


)
}


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.