2

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>

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

1 Comment

This should be marked as the answer. It is correct and the solution works well. Although I will add that the cat.services.map(... is not closed correctly, you will need an additional parenthesis to close.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.