Omortis Omortis - 1 year ago 76
React JSX Question

uncontrolled <select> default value in ReactJS

How does one set the default value of an uncontrolled

<select>
in a JSX stanza? I have many controlled
<select>
's in flight, I know the difference.

<select
// defaultValue="Select a type"
// value="Select a type"
onChange={ this.handleTypeSelect.bind(this, event) }
>
<option value="" disabled selected>Select a type</option>
<option value="type1">type1</option>
<option value="type2">type2</option>
</select>


Running the code above as-is generates the dreaded:

Warning: Use the defaultValue or value props on <select> instead of setting
selected
on <option>


Removing the
selected
line and uncommenting the
value
or
defaultValue
lines removes the console warning but has no effect in the browser at all (as in the default value does not show up).

What am I missing?

Answer Source

defaultValue takes the value of the default option you want selected. Your option Select a type has no value.

If you do <option value="-1">Select a type</option> then defaultValue={-1} it should work.

<select defaultValue={-1} onChange={ this.handleTypeSelect.bind(this, event)}>
    <option value="-1" disabled>Select a type</option>
    <option value="type1">type1</option>
    <option value="type2">type2</option>
</select>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download