Generating groupings within a Material UI Select component dynamically from data

Viewed 3780

I need to generate the groupings of my Select component dynamically and would like to use the component in a controlled way. (As opposed to uncontrolled.)

This code snippet works fine without the <ListSubheader ...> component, however I need it and the Material UI Docs example for group select shows using the <ListSubheader ...> component in this way.

  <Select fullWidth value={selectedPlan} onChange={handleChange}>
        {products?.map(p => (
          <>
            <ListSubheader>{p.name}</ListSubheader>
            {p.plans.map(pl => (
              <MenuItem key={pl.id} value={pl}>
                {pl.id} {pl.name} {pl.type} {pl.price}
              </MenuItem>
            ))}
          </>
        ))}
      </Select>

However it seems impossible to generate this dynamically if we are getting the error message

The Menu component doesn't accept a Fragment as a child. Consider providing an array instead.

According to the Material UI documentation,

⚠️The MenuItem elements must be direct descendants when native is false.

How can I programatically generate my groupings in my component.

I have created a code sandbox where this problem is reproducible

2 Answers

Here is the edited sandbox.

Yes, the issue was that you had it wrapped in a fragment. If you wrap it in a <div> it works but returns undefined for event.target.value since <MenuItem/> is not a direct child of <Select/>.

P.S. I extracted it to a function just make it more clear. It has nothing to do with the fix.

Related