How to put 'selected' on <option>?
jkleiser opened this issue · comments
I'm struggling with a very basic problem. I have created a <select>
with a few <option>
elements, but I cannot figure out how to make a certain <option>
the selected one. I have a function that generates the <option>
element, and it currently looks like this:
const renderMyOption = (obj, selNo, i) =>
selNo == i ?
<option value={i} selected>{obj.title}</option> :
<option value={i}>{obj.title}</option>
I have also tried to put the condition and the selected
inside the <option>
, but I have found no way that works.
What confused me was that the selected
attribute did not show when I inspected the elements in my browser (Brave and Safari). A little more testing, however, showed that manipulating my selNo
in the state actually caused my <select>
to respond correctly. I have now put the condition inside my <option>
like this:
const renderMyOption = (obj, selNo, i) =>
<option value={i} selected={selNo == i}>{obj.title}</option>