Reputation: 399
I'm using Material-UI's Select component in one of my React projects. I require the dropdown data to be shown in groups, hence I'm using <MenuItem>
wrapped around <ListSubheader>
. I'm having a hard time getting the value of my MenuItem
s. Please let me know if there's anything blatantly wrong with my code.
<FormControl>
<InputLabel>Product type</InputLabel>
<Select
id="product-type"
input={<Input id="grouped-select" />}
value={this.state.productType}
autoWidth={true}
style={{ width: 200 }}
onChange={(e, child) => {
console.log(e.target.value); // undefined!
}}
>
{this.state.productList.map((p, i) => {
const list = p[1];
let items = list.map((e, j) => {
return (
<MenuItem key={j} value={e.name}>
{e.name}
</MenuItem>
);
});
return (
<div>
<ListSubheader key={i}>{p[0]}</ListSubheader>
{items}
</div>
);
})}
</Select>
</FormControl>
Upvotes: 6
Views: 6404
Reputation: 399
The reason e.target.value
was returning undefined was, as others mentioned, due to the fact that MenuItem
wasn't a direct child of Select
. Since productList
is dynamically being set into the dropdown, it has to be rendered in such a way:
ListSubheader0
Item0
Item1
ListSubheader1
Item2
Item3
Item4
...
...
Instead of wrapping my ListSubheader
and MenuItem
in a div
tag where reading the target.value
was impossible, I returned an array.
return [
<ListSubheader key={i}>
{p[0]}
</ListSubheader>,
items
];
Upvotes: 8
Reputation: 5768
Material-ui Select direct children must be MenuItem:
⚠️The MenuItem elements must be direct descendants when native is false.
You need to change your code accordingly so MenuItem
is direct child of Select
. Something like:
<MenuItem key={i} value={p[0]}>
<ListSubheader key={i}>{p[0]}</ListSubheader>
{items}
</MenuItem>
It may look different, but e.target.value
will not be undefined now.
Upvotes: 1