Reputation: 11
I wrote the following code but with error:
index.js: 1 Warning: Use the defaultValue
or value
props on <select>
instead of setting selected
on <option>
.
I faced
<div className='form-group'>
<label>Parent category</label>
<select
name='category'
className='form-control'
onChange={(e) => setParent(e.target.value)}
defaultValue={parent}
>
<option>Please select</option>
{categories.length > 0 &&
categories.map((c) => (
<option selected={c._id} key={c._id} value={c._id === parent}>
{c.name}
</option>
))}
</select>
</div>
Upvotes: 0
Views: 4738
Reputation: 721
You should not put selected
property in the option
. Rather use the value
property of select
.
And always follow this rule that either the component can be controlled or uncontrolled. If you are using a setter in onChange, then don't use defaultValue
. Use the value
property and set it with the state variable.
Your code should look something like this (or find a working codesandbox link here):
<div className="form-group">
<label>Parent category</label>
<select
name="category"
className="form-control"
onChange={(e) => setParent(e.target.value)}
value={parent}
>
<option>Please select</option>
{categories.length > 0 &&
categories.map((c) => (
<option key={c._id} value={c._id}>
{c.name}
</option>
))
}
</select>
</div>
Upvotes: 3