简体   繁体   中英

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

How to resolve this warning?

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

This has been asked once before but the solution does not help me. I cannot set selected because the value here is from a Redux state (if present). If redux state has no values, it should show default option - "Select gender"

Here is my code:

import React, { Component } from 'react'
import InputGender from '../../edit-profile/gender-input'
...
...

<InputGender value={gender} change={this.change} />

And here is InputGender

import React from 'react'
import PropTypes from 'prop-types'
import Select from '../others/input/select'

const InputGender = ({ value, change }) => (
  <div className="edit_gender_div">
    <Select
      placeholder="Select option"
      value={value}
      valueChange={e => change('gender', e)}
      className="edit_gender mb-2"
    >
      <option value="" disabled selected>
        Select Gender
      </option>
      <option>Male</option>
      <option>Female</option>
      <option>Other</option>
    </Select>
  </div>
)

InputGender.propTypes = {
  value: PropTypes.string.isRequired,
  change: PropTypes.func.isRequired,
}

export default InputGender

Remove selected attribute from option. The value props will set the selected value in the option automatically (handled by react).

<option value="" disabled selected>
{/* remove selected attribute ^^ */}

It should just be:

<option disabled>

You have to make some changes.

send '' if you want to select disabled option or gender value to select other values <InputGender value={gender} change={this.change} />

And options should be like this.

<option value="" disabled>{/* no need of selected */}
    Select Gender
  </option>

If you want to select an option case, you need to write goal option value into the value depended on the select tag like this:

<select value="first">
  <option value="first">First</option>
  <option value="second">Second</option>
</select>

As I know, if you want to capture onChange hook on every form tag, you need to use the onChange attr for every form's input. So please change it to this:

<Select
      placeholder="Select option"
      value={value}
      onChange={e => change('gender', e)}
      className="edit_gender mb-2"
    >
 ...

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