Norayr Ghukasyan
Norayr Ghukasyan

Reputation: 1408

Mui Select chooses the first option as selected when using grouping

Mui Select strangely selects the first option on it's first render when using grouping.

const generateOptions = useCallback((options: ISelectOption[]) => {
  return options.map((opt, ind) => {
    if (opt.groupOptions) {
      return [
        <ListSubheader key={opt.label}>{opt.label}</ListSubheader>,
        opt.groupOptions.map((val) => (
          <MenuItem key={ind} value={val.value}>{val.label}</MenuItem>
        ))
      ]
    }

    return (
      <MenuItem key={ind} value={opt.value}>{opt.label}</MenuItem>
    )
  })
}, [options])

<FormControl fullWidth className="fb">
  <InputLabel id="select-label">{label}</InputLabel>
  <Select
    name={name}
    value={value}
    label={label}
    disabled={disabled}
    id="select-label"
    labelId="select-label"
    multiple={!!multiple}
    IconComponent={IconComponent}
    onChange={handleChange}
  >
    {generateOptions(options)}
  </Select>
</FormControl>

The options are an array of this shape.

interface ISelectOption {
  data?: any;
  label: string;
  className?: string;
  value: string | number;
  groupOptions?: ISelectOption[];
  renderOption?: (option: ISelectOption) => React.ReactNode;
}

And these are the Select options.

[
    {
        "label": "B2C campaigns",
        "value": "B2C campaigns",
        "groupOptions": [
            {
                "label": "Campaign 1",
                "value": 1
            }
        ]
    },
    {
        "label": "B2B campaigns",
        "value": "B2B campaigns",
        "groupOptions": [
            {
                "label": "Campaign 2",
                "value": 2
            }
        ]
    }
]

The initial value of the value property is an empty string, but somehow Mui chooses the first option as selected. And this is clearly mentioned in the Mui docs. enter image description here The  element here has .Mui-Selected className

When you remove the <ListSubheader> elements, you can see that it is starting to work as expected.

The input value. Providing an empty string will select no options. Set to an empty string '' if you don't want any of the available options to be selected.

The version of Mui is

"@mui/material": "^5.10.8",

Upvotes: 2

Views: 1405

Answers (1)

Dobromir Kirov
Dobromir Kirov

Reputation: 1033

You have declared defaultValue={value} as well as value={value}, the default value is set only when the component is uncontrolled. This is mentioned in the <Select /> api before the value description.

The default value. Use when the component is not controlled.

Upvotes: 1

Related Questions