Search code examples
javascripthtmljsonreactjsdropdown

how to display json data in dropdown using reactj


i need to display data in dropdown i haven given json data with code.

        this.setState({
           data : [
                         {id:1,type:A},
                         {id:1,type:B},
                         {id:1,type:C},
                   ]
                })


            <select className="form-control"  onChange={(e) => this.handleChange(e)}  >
                    <option >Select data</option>
                        {
                        this.state.data.map((i, h) => 
                        (<option key={h} value={i.type}>{i.type}</option>))
                        }
            </select>   

Solution

  • Json isn't correct...put quotation for string type value-"A", "B", "C"

    data: [{ id: 1, type: "A" }, { id: 1, type: "B" }, { id: 1, type: "C" }]
    

    JSX

    class App extends Component {
      state = {
        data: [{ id: 1, type: "A" }, { id: 1, type: "B" }, { id: 1, type: "C" }]
      };
      handleChange = e => {
        console.log(e.target.value);
      };
      render() {
        return (
          <div>
            <select className="form-control" onChange={this.handleChange}>
              <option>Select data</option>
              {this.state.data.map((i, h) => (
                <option key={h} value={i.type}>
                  {i.type}
                </option>
              ))}
            </select>
          </div>
        );
      }
    }