mui / mui/material-ui

[material-ui][Select] alternative option for select multiple behavior, that item click replaces existing selection instead of adding it

Open
#43,813 2 comments 0 reactions 1 assignee View on GitHub

@DiegoAndai is already working on this.

Since Sep 19, 2024.

scope: select type: new feature
Dominant language
JavaScript
Stars
99.1k
Forks
32.5k
Avg merge
2d 17h
Merged PRs (30d)
106

Description

Summary

Currently, an item click in <Select multiple /> is handled as toggling:

  • if it is already selected, remove it from the selected value array.
  • if it is not selected yet, append it into the selected value array.

On the other hand, HTML native <select multiple /> behaves like this:

  • Bare click replaces already selected value, results in setting the selected value array to the singleton of the latest selected element.
  • The selected item is toggled, rather than replaced, when selected by Ctrl+Click.
  • There is also range selection Shift+Click (but it behaves somewhat strange when some of the items are already selected)

I want a material multi-select component except that it should behave like native multi-select, since my component expects multi-select sometimes but not very frequently. Range select(Shift+Click) is not needed. Does current MUI provide such option? If it does not, then I would like to suggest to add it.

Examples

I skimmed the code and apparently this is the section in charge for current behavior.
https://github.com/sai6855/material-ui/blob/master/packages/mui-material/src/Select/SelectInput.js#L269

If we should add the implementation, probably adding a new boolean nativeLike prop and fixing the logic like below would help..?
I haven't tested if this works. I will make some PR if it seems like a good idea.

    if (multiple) {
      if (nativeLike && !event.ctrlKey) {
        newValue = [child.props.value]; // NEW: replacing instead of toggling selection
      } else {
        newValue = Array.isArray(value) ? value.slice() : [];
        const itemIndex = value.indexOf(child.props.value);
        if (itemIndex === -1) {
          newValue.push(child.props.value);
        } else {
          newValue.splice(itemIndex, 1);
        }
      }
    } else {
      newValue = child.props.value;
    }
Motivation

It would be nice to have an another option for multiple select which behave more similarly to HTML native multiple select.

Search keywords: select multiple behavior

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.