简体   繁体   中英

How to display all values from a json api into a single dropdown list using React JS?

I have a page written in React JS that consist of a dropdown list. The values in the dropdown-list are populated from a json file that has over a 100 clients. The dropdown-list in my page presents the user with the clients, but the issue am encountering is: it displays the clients in individual dropdown-lists and my goal is to get all client into a one /single dropdown-list.

this is just one of the 100 arrays in the json file:

[
    {
        "id": 777,
        "abc_programid": "777777-1111-2222-333-444444",
        "clientName": "client one - AB"
    }
]

The code:

import React, { Component } from 'react';
class Acl extends Component {

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

    componentDidMount() {
        fetch('http://myClientapi/api/', {
            method: 'GET',
            headers: {
                'Content-type': 'application/json',
                'Authorization': 'Bearer abc.123.456'
            },
        })
        .then(results => results.json())
        .then(data => this.setState({ data: data }))
    }

    render() {
    console.log(this.state.data);
    return (
    <div>
        <div className="container">
            <form>
            <h2>Memeber Selection:</h2>
            <div>
                {
                    this.state.data.map(item =>(
                        <div>
                            <select className="custom-select" id="clientName">>
                            <option key={item.clientName}>{item.clientName}</option>
                            </select>
                        </div>
                    ))
                }
            </div>
            <div>
            <button type="submit" className="btn btn-primary">Submit</button>
            </div>
            </form>
        </div> 
    </div>
        );
      }
}

export default Acl

...my problem: My page is displaying 100 drop-downs and each one has an individual client; My goal: to get all clients into one single dropdown. Could I get some help with this please?

Move the <select> outside of the mapping loop and only return <option> in map callback

<div>
  <select className="custom-select" id="clientName">
    { this.state.data.map(item =>(
       <option key={item.clientName}>{item.clientName}</option>
    )) }
  </select>
</div>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM