mui / material-ui

Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
https://mui.com/material-ui/
MIT License
94.02k stars 32.3k forks source link

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

Open paulsohn opened 2 months ago

paulsohn commented 2 months ago

Summary

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

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

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

mnajdova commented 2 months ago

We have the NativeSelect for cases like this, check this CodeSandbox: https://codesandbox.io/p/sandbox/falling-star-f8576k?file=%2Fsrc%2FDemo.tsx. The caveat is that the styles look differently that the Material UI's select.

paulsohn commented 1 month ago

@mnajdova Thank you for verification. Yes I am aware of this component, and also that native option like <Select native multiple> gives me the identical result. However, as you also noted by yourself, the native select itself does not apply for my case due to the UI consistency requirements. That is why I opened this issue.