'React - Adding a default Option while using map in Select Tag

I learnt that when using Select each element in the dropdown is given by Option tag.

Now i have an array of values the dropdown must contain-

a = ['hai','hello','what']

So i optimised my code by writing it as follows -

     <Select>  
          a.map(ele =>
        <Option value={ele}> ele </Option> )
     </Select>

This worked successfully. But now i want to add a default value to be shown on first render. I tried doing this -

<Select>
      <Option selected={true}> Choose from the list</Option
      a.map(ele =>
            <Option value={ele}> ele </Option> )
</Select>

But this gives an error. What is the right way to do it?



Solution 1:[1]

Use the second parameter of the map for the index. And the index === 0 then it would be selected.

<Select>
      <Option value=""> Choose from the list</Option
      a.map((ele, index) => <Option value={ele} selected={index === 0}> {ele} </Option>)
</Select>

Solution 2:[2]

You can try this :

<Select name="select" id="select" >
    {
        a.map(ele => (
            <option key={ele} >{ele}</option>
        ))
    }
</Select>

Solution 3:[3]

React recommends using default value. If you replace selected with defaultValue you can solve the problem.

<select>
<option defaultValue={true}>Choose From List</option>
{
    a.map((ele,index)) => <option key={index}>{ele}</option>
}
</select>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sajeeb Ahamed
Solution 2 Mahdi Ezzahir
Solution 3