Omortis Omortis - 1 year ago 59
React JSX Question

uncontrolled <select> default value in ReactJS

How does one set the default value of an uncontrolled

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

// 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>

Running the code above as-is generates the dreaded:

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

Removing the
line and uncommenting the
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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download