hardy
hardy

Reputation: 901

MenuItem with dynamic value is not working in Material UI React

I am using Select, in Material UI for React, I always get undefined when i select from selector. It always happen when we use MenuItem value dynamic. But if i use static value instead of using dynamic, it works well. But I have to use in dynamic way with .map operator.

Please provide the solution which works well in dynamic value.

Like this -> <MenuItem value={SOME-DYNAMIC-VALUE} />

this.state.selectedTagetIdentity = '';

onTargetIdentityChange = (event) => {
  this.setState({ selectedTagetIdentity: event.target.value }); // its undefined always 
}

const splitedIdenties = { 
 'abc1' :[{ id: 12, age: '2' },{ id: 13, age: '3' }], 
 'abc2': [{ id: 14, age: '22' },{ id: 15, age: '25' }] 
};
<Select value={selectedTagetIdentity} onChange={onTargetIdentityChange}>
  {Object.keys(splitedIdenties).map((identityTypeKey, identityTypeIndex) => 
    <div key={identityTypeIndex}>
      <ListSubheader>{identityTypeKey}</ListSubheader>
      {splitedIdenties[identityTypeKey].map(identity => 
        <MenuItem key={identity.id} value={identity.id}>{identity.age}</MenuItem>
        )}
    </div>
  )}
</Select>

See here it's not working

Upvotes: 1

Views: 3467

Answers (1)

Ido
Ido

Reputation: 5748

The issue is you are wrapping MenuItem with div. MenuItem elements must be direct descendants of material-ui Select:

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

To fix that, remove the wrapping div:

<Select value={personName} onChange={onTargetIdentityChange}>
    {Object.keys(splitedIdenties).map((identityTypeKey, identityTypeIndex) =>{
    let children = [];

    children.push(<ListSubheader>{identityTypeKey}</ListSubheader>); 
      splitedIdenties[identityTypeKey].forEach(identity => {
        children.push(<MenuItem key={identity.id} value={identity.id}>{identity.age}</MenuItem>)
      })

      return children;
    }
  )}
</Select>

Edit Invisible Backdrop

Upvotes: 6

Related Questions