javascriptreactjsmaterial-uimaterial-table

How to select multiple values in a dropdown and then show as comma separated string in material table react?


I'm trying the editComponent feature to have a dropdown in React's material table to select multiple options and show them as a comma separated string.
Example : If user selects option1,option3 then in the material table cell it would show the value as 'option1,option3' as one string.
Here is a code below of what I attempted but not sure what to put in selected and handleChange to make it work :

    {title:'Root Causes',field:'rootCauses', editComponent: (props)=>(
        
        <Select
        label = 'Root Cause'
        multipe={true}
        selected={props.values.join(',')??}
        onChange={ ? }
        >
        {["option1","option2","option3","option4"].map((option) => (
          <MenuItem key={option} value={option}>
            {option}
          </MenuItem>
        ))}
        </Select>
    )}

Solution

  • to manage the multiple values, MUI select event returns the array of selected items, so you've to store those items only. And no need to join those manually, Select handles that.
    As per the MUI documentation:

           <Select
              labelId="demo-multiple-name-label"
              multiple
              value={props.values}
              onChange={handleChange}
            >
              {["option1","option2","option3","option4"].map((option) => (
                <MenuItem
                  key={option}
                  value={option}
                >
                  {option}
                </MenuItem>
              ))}
            </Select>
    
    

    And the handleChange function would be something like this (I'm assuming that the props is receiving the setValues fn as well)

      const handleChange = (event) => {
        const {
          target: { value },
        } = event;
        props.setValues(
          // On autofill we get a stringified value.
          typeof value === 'string' ? value.split(',') : value,
        );
      };
    
    

    For Reference: MUI multiple Select documentation