简体   繁体   中英

React Select not allowing multiple selections

I have a react app that I am currently updating which involves switching to react 16.8 and updating all libraries. I have two drop down selects from material UI, and due to this new version the multi select one no longer allows multiple options to be selected and I can't work out why. Any ideas would be appreciated!

Code:

import React from 'react';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';

const names = [
  'Oliver Hansen',
  'Van Henry',
  'Kelly Snyder',
];



export default function MultipleSelect() {
  const [personName, setPersonName] = React.useState([]);

  const handleChange = event => {
  console.log(event) //holds the selected option correctly
  setPersonName(event.target.value);
    console.log(personName) 
  };

  return (
    <div>
      <FormControl className={classname}>
        <Select
          multiple //used to be isMulti but this also no longer works
          value={personName}
          onChange={handleChange}  
          placeholder = {"choose a name"}
          options={names}
        >
        </Select>
      </FormControl>
    </div>
  );
}

This is because your value always contains a single string value. When you select a second items, it overrides the first value with new one. You need to assign an array of values to value prop with selected values. Push selected item in previously selected values array and update the state and on removal, remove that name from that array.

 export default function MultipleSelect() { const [selectedNames, setSelectedNames] = React.useState([]); const handleChange = event => { console.log(event) //holds the selected option correctly // if selection/addition setSelectedNames([...selectedNames, event.target.value]); // On removal, // setSelectedNames(selectedNames.filter(name => name !== event.target.value)); }; return ( <div> <FormControl className={classname}> <Select multiple //used to be isMulti but this also no longer works value={selectedNames} onChange={handleChange} placeholder = {"choose a name"} options={names} > </Select> </FormControl> </div> ); }

Set true value to multiple attribute:

   <Select
              multiple="true"
             // ...
            >
              // ...
            </Select>

Your options are currently single string. Select expects something like this (notice the value and label properties):

[
  {value: 1, label: "Oliver Hansen"},
  {value: 2, label: "Van Henry"},
  {value: 3, label: "Kelly Snyder"}
]

If you have that in order your select should be working as expected.

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