简体   繁体   中英

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

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>

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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM