How to use option value in React Select

Viewed 2677

I am learning react and it's fun!

I am creating a sign up form in React using react-select.

I am mapping values from array:

const options = [ 'female', 'male', 'other']

<Select {...register("gender")} 
          label="Gender"
          fullWidth 
          variant="outlined"
          >
      {options.map(value => (
        <option key={value} value={value}>
          {value}
        </option>
      ))}
      </Select>

But I get following warning:

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

Questions:

  1. How do I use the defaultValue or value props on ?
  2. I am setting label="Gender" but it is not visible, why?

sign up form

1 Answers
const options = [
  { value: "female", label: "Female" },
  { value: "male", label: "Male" },
  { value: "other", label: "Other" }
];

export default function App() {
  const [gender, setGender] = useState("");

  const handleChange = (event) => {
    setGender(event.target.value);
  };

  return (
    <div className="App">
      <Select
        value={gender}
        onChange={handleChange}
      >
        {options.map((option) => (
          <MenuItem key={option.value} value={option.value}>
            {option.label}
          </MenuItem>
        ))}
      </Select>
    </div>
  );
}

API reference: https://material-ui.com/api/select/

Working demo: https://codesandbox.io/s/pedantic-jones-dyfwd?file=/src/App.js:119-788

Related