Search code examples
reactjsmaterial-uimultiple-select

Multiple select in Material Table


I want to have a multiple select when editing a row. This is currently what I have

My current table

I want to change it to multiple select, and whenever I add more items, it gets appended to the Tank column as a string. This is the code for my columns :

    const columns = [
    {
        title: "Level",
        field: 'sequence',
        editable: 'onAdd',
    },
    {
        title: 'Tank',
        field: 'tankNo',
    },
    {
        title: "Select ",
        field: 'tankNo',
        lookup: { 'test1': 'select1', 'test2': 'select2' }
    }
];

Solution

  • You will need to set multiple to true for the Select and use an array to store the value instead of string

    Updated usage with material table

    
          {
            title: "Select ",
            field: 'tankNo',
            editComponent: (props) => {
              const { value, onChange } = props;
              return (
               <Select
                labelId="labelId"
                id="selectId"
                multiple={true}
                value={value}
                onChange={(event) => {
                  const {
                    target: { value }
                  } = event;
                  onChange(typeof value === "string" ? value.split(",") : value);
                }}
              >
                {["Select 1", "Select 2", "Select 3"].map((option) => (
                  <MenuItem key={option} value={option}>
                    {option}
                  </MenuItem>
                ))}
              </Select>
            );      
         }
        }
    
    
            const [values, setValues] =  useState([])
    
    
            handleChange =  event => {
             const {
              target: { value },
             } = event;
             setValues(
             typeof value === 'string' ? value.split(',') : value,
             );
            }
           
    
             <Select
              labelId="labelId"
              id="selectId"
              multiple={true}
              value={values}
              onChange={handleChange}
            >