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?
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>
You can try this:
<Select name="select" id="select" > { a.map(ele => ( <option key={ele} >{ele}</option> )) } </Select>
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.