Home > Back-end >  How to created a optgroup in select v4 mui component by mapping over an array to avoid code duplicat
How to created a optgroup in select v4 mui component by mapping over an array to avoid code duplicat

Time:01-08

I am trying to create a dynamic v4 mui select , that will render value and options related to that value , the current issue is since I am mapping in a div, the current value is undefined , please check the code sandbox example... how to make this value identifiable by the handle change ?... technically there is no way to catch the pressed on value in the dropdown... since it has to be on the surface and by mapping I am pushing it a one level down..

 {arr?.map((option, i) => (
            <div key={i}>
              <ListSubheader>{option}</ListSubheader>
              <MenuItem key={option}>{objectData[option]}</MenuItem>
            </div>
 ))}

Code Sandbox

CodePudding user response:

Typically in React, you would solve an issue like this by wrapping the elements in a <Fragment> (<>...</>). However, the <Select> MUI component does not accept this, so return an array containing each component from your map callback instead.

{
  arr?.map((option, i) => [
    <ListSubheader>{option}</ListSubheader>,
    <MenuItem
      key={option}
      value={objectData[option]}
    >
      {objectData[option]}
    </MenuItem>,
  ]);
}

Hope this helps.


Links:

  • Related