简体   繁体   中英

Material UI Multiple Select | How to use Multiple Select with arrays

I'm using material-ui multiple select and I've created an example based on the documentation provided from Multiple Select .

My example here: codesandbox

In my example, I want to use 2 arrays for multiple select dropdowns, 1 for each. I tried to achieve this by updating the handleChange event from:

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

to:

const handleChange = event => {
    setState({ ...state, [event.target.name]: event.target.value });
  };

When I test this update, I click on any name from the drop-down and I get this error: state.indexOf is not a function

I want to be able to use the handleChange event to work for all of the multiple select drop-downs for my example. Any help or suggestions are much appreciated.

In your codesandbox, you have used only one array as state which should be changed to two

  const [state, setState] = React.useState({ first: [], second: [] });

For each select we have to give the name

<Select
      labelId="demo-mutiple-checkbox-label"
      id="demo-mutiple-checkbox"
      multiple
      value={state.first}
      name="first"
      onChange={handleChange}
      input={<Input />}
      renderValue={selected => selected.join(", ")}
    >

this is the working csb link https://codesandbox.io/s/material-demo-s1g4h?file=/demo.js:1322-1618

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