Search code examples
reactjsmaterial-uimultipleselection

How do I set a limit to max number of selections in multi select menu in Material UI react


I have a multi select menu from material UI component and I need to make sure that users can only choose three options from that menu as I need to send that value as props. Now, what should I do to ensure that? Here is the code that I am using:

<FormControl sx={{ m: 2, width: "100%" }}>
    <InputLabel id="demo-multiple-chip-label">Location</InputLabel>
    <Select
      labelId="demo-multiple-chip-label"
      id="demo-multiple-chip"
      multiple
      value={selectedLocations}
      onChange={handleChange}
      input={<OutlinedInput label="Location" />}
      
      renderValue={(selected) => (
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
          {selected.map((value) => (
            <Chip key={value} label={value} />
          ))}
        </Box>
      )}
      MenuProps={MenuProps}
    >
      {locationList.map((location: string,index: number) => (
        <MenuItem
          key={index}
          value={location}
          style={getStyles(location, selectedLocations, theme2)}
        >
          {location}
        </MenuItem>
      ))}
    </Select>
</FormControl>

The options that I am going to select are getting stored in selectedLocations. Now, what should I do to make sure that a user can not choose more than three options.

I was unable to find any info on this anywhere, including MUI documentation.

Expected Results: Only choose three options from the dropdown list

Link to how the dropdown looks in general


Solution

  • I don't think there is an API provided in Select or Select.MenuProps for limiting the maximum number of selected options.

    However, this can be achieved by disabling the options that are not selected whenever the maximum number of selected options is reached:

    {locationList.map((location: string, index: number) => (
      <MenuItem
        key={index}
        value={location}
        disabled={selectedLocations.length >= 3 && !selectedLocations.includes(location)}
      >
        {location}
      </MenuItem>
    ))}
    

    Live Demo