jrock2004
jrock2004

Reputation: 3501

MUI Group Select - Array of Array

So I want to create a group MUI select and having some issues. I want to build the select options via data coming from an API.

const data = [
    {
      id: '1',
      name: 'Category 1',
      services: [
        {
          id: '1',
          name: 'Service 1',
        },
      ],
    },
    {
      id: '2',
      name: 'Category 2',
      services: [
        {
          id: '1',
          name: 'Service 1',
        },
      ],
    },
  ];

So I have the following react code but when when I select an option, nothing happens. So I am just not sure what I am doing wrong here.

<FormControl sx={{ m: 1, minWidth: 120 }}>
  <InputLabel htmlFor="grouped-select">Grouping</InputLabel>
  <Select defaultValue="" id="grouped-select" label="Grouping">
    {data.map((cat) => (
      <div key={cat.id}>
        <ListSubheader>{cat.name}</ListSubheader>

        {cat.services.map((service, index) => {
          return (
            <MenuItem key={service.id} value={service.id}>{service.name}</MenuItem>
          );
        })}
      </div>
      ))}
    )
  </Select>
</FormControl>

Upvotes: 2

Views: 1175

Answers (1)

Tam&#225;s Katona
Tam&#225;s Katona

Reputation: 833

You should not put any wrapper element around your list items (<div key={cat.id}>)

<Select defaultValue="" id="grouped-select" label="Grouping">
    {data.reduce((listItems, cat) => [
        ...listItems,
        <ListSubheader>
            {cat.name}
        </ListSubheader>,
        ...cat.services.map((service, index) => (
            <MenuItem key={service.id} value={service.id}>{service.name}</MenuItem>
        )),
    ], [])}
</Select>

Upvotes: 5

Related Questions