'Generating groupings within a Material UI Select component dynamically from data
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
Solution 1:[1]
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.
Solution 2:[2]
I had the same problem with the selector and it helped me to replicate some of this code https://codesandbox.io/s/mui-select-grouping-problem-i9jtj?file=/src/App.js:1662-1704 if the component expects you to take a single array and not a group try a reduce() like this https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ederson Fajardo |