React material UI close when the value selected - multi select

Viewed 2865

I am using react material UI for building my components. I am using react multi-select to get multiple values from the user.

<FormControl className={clsx(classes.formControl, classes.noLabel)}>
        <Select
          multiple
          value={personName}
          onChange={handleChange}
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
          }}
          input={<Input />}
          renderValue={(selected) => {
            if (selected.length === 0) {
              return <em>Placeholder</em>;
            }

            return selected.join(", ");
          }}
          MenuProps={MenuProps}
          inputProps={{ "aria-label": "Without label" }}
        >
          <MenuItem disabled value="">
            <em>Placeholder</em>
          </MenuItem>
          {names.map((name) => (
            <MenuItem
              key={name}
              value={name}
              style={getStyles(name, personName, theme)}
            >
              {name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

It's working fine. But I need to close the dropdown when the user selects the value. But now it's closed only when the blur event triggers.

Is there any option to close the dropdown when the user selects any values?

Thanks in advance

1 Answers

Probably you can solve this by using the useRef hook. Add the reference to the select and in the change handler you can try to close it by using ref.current.close().

import React , {useRef} from 'react';
const ref = useRef()
<FormControl className={clsx(classes.formControl, classes.noLabel)}>
        <Select
          multiple
          value={personName}
          onChange={handleChange}
          ref={ref}
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
          }}
          input={<Input />}
          renderValue={(selected) => {
            if (selected.length === 0) {
              return <em>Placeholder</em>;
            }

            return selected.join(", ");
          }}
          MenuProps={MenuProps}
          inputProps={{ "aria-label": "Without label" }}
        >
          <MenuItem disabled value="">
            <em>Placeholder</em>
          </MenuItem>
          {names.map((name) => (
            <MenuItem
              key={name}
              value={name}
              style={getStyles(name, personName, theme)}
            >
              {name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      
      const handleChange = (event) =>{
      ....
      ref.current.close();
      }

Related