'Material UI Select Field multiselect

I tried several times the example given in the documentation. but it didn't work well for me. can any one help me.... this is the code

import React, {Component} from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

const names = [
  'Oliver Hansen',
  'Van Henry',
  'April Tucker',
  'Ralph Hubbard',
  'Omar Alexander',
  'Carlos Abbott',
  'Miriam Wagner',
  'Bradley Wilkerson',
  'Virginia Andrews',
  'Kelly Snyder',
];

/**
 * `SelectField` can handle multiple selections. It is enabled with the `multiple` property.
 */
export default class SelectFieldExampleMultiSelect extends Component {
  state = {
    values: [],
  };

  handleChange = (event, index, values) => this.setState({values});

  menuItems(values) {
    return names.map((name) => (
      <MenuItem
        key={name}
        insetChildren={true}
        checked={values && values.indexOf(name) > -1}
        value={name}
        primaryText={name}
      />
    ));
  }

  render() {
    const {values} = this.state;
    return (
      <SelectField
        multiple={true}
        hintText="Select a name"
        value={values}
        onChange={this.handleChange}
      >
        {this.menuItems(values)}
      </SelectField>
    );
  }
}

http://www.material-ui.com/#/components/select-field

the select property works but it doesnt select multiple options. when i check the states.value it only includes a single value not a array of values



Solution 1:[1]

A much better approach is possible. In the lasted version of material UI.

import Select from '@material-ui/core/Select';
import MenuText from '@material-ui/core/MenuText';
import {useState} from 'react';

const App = () => {
   const [selected,setSelected] = useState([]); 
   return <Select multiple={true} value={selected} onChange={(event) => setSelected(event.target.value)}>
   <MenuItem>Val - 1</MenuItem>
   <MenuItem>Val - 2</MenuItem>
   <MenuItem>Val - 3</MenuItem>
   <MenuItem>Val - 4</MenuItem>
</Select> 
}

Make sure to set the value of select as an array. Otherwise, It will not work

Solution 2:[2]

This worked for me for old material ui version. You can add multiple items and deselect to remove them.

handleChange(event, index, values)  { 
   this.setState({ 
     values: [...values]
   });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leonardo Maffei
Solution 2 monika maheshwari