Ad

How Keep A Specific Element Pre-selected In Dropdown?

- 1 answer

I am displaying dynamic dropdown, where I want to keep one specific element or first element selected. But I could not find way.

<select onChange = {this.handleSelectChange}>                 
    <option>any-select</option>
    {                     
        this.state.data2.map(function(data) {                
          return  <option value={data.id}>{data.name}</option>                                                             
        })         
    }                    
</select>
Ad

Answer

you can use below mentioned code

 this.state.data2.map(function(data,index) {                
     return index==0?<option value={data.id} selected="selected">{data.name}</option>:<option value={data.id}>{data.name}</option>                                                            
    })   
Ad
source: stackoverflow.com
Ad