Search code examples
reactjsselectdropdown

how to set options in Select dropdown from an array returned from webservice in react js


Im new to react trying to populate the dropdown with the data i receive from webservice...

the webservice data i get is in the following format

       {
           "status":1,
           "yearList":[{"year":"2021","fromDate":null,"toDate":null},
                      {"year":"2021","fromDate":null,"toDate":null},
                      {"year":"2021","fromDate":null,"toDate":null},
                      {"year":"2021","fromDate":null,"toDate":null},
                      {"year":"2021","fromDate":null,"toDate":null}]

        }
     I need my select dropdown to be populated only with the year field.....

   This is the code....where im setting the state with data from webservice
        this.taxService.getFinancialYearsList().then(data=>{
        console.log(" year data is "+JSON.stringify(data))
        if(data.status == 1)
         {          
           this.setState({yeardata:data?.yearList})
          
    }
})

       and in render
        <select className="select2 form-control required finyear"  
         disabled={false}
         value={this.state.yearSelected}
         onChange={(e)=> 
            this.setState({yearSelected:e.currentTarget.value})}
            >
                                                    
          {this.state.yeardata?.map((item,i)=>{
           <option key={i} value={item.year}>
            {item.year}
            </option>
             })}
            </select>

Nothing is getting populated...the console.log is printing the data correctly like i mentioned in the starting of my question


Solution

  • Try with this code

                      <select
                              disabled={false}
                              value={select}
                              onChange={(e) => setSelected(e.currentTarget.value)}
                          >
                              {webserviceData.yearList.map((item,index) => (
                              <option key={index} value={item.year}>
                                  {item.year}
                              </option>
                              ))}
                          </select>