ReactJS Select-box optgroup with dynamic data

35 Views Asked by At

I want to display JSON data in my select box. My JSON Data is

const myDaya = [
  { mainGroup: '', label: 'My Option1', value: 'Option1' },
  { mainGroup: '', label: 'My Option2', value: 'Option2' },
  { mainGroup: 'Group1', label: 'Group1 Option1', value: 'Option1-Value' },
  { mainGroup: 'Group1', label: 'Group1 Option2', value: 'Option2-Value' },
  { mainGroup: 'Group1', label: 'Group1 Option3', value: 'Option3-Value' },
  { mainGroup: '', label: 'My Option3', value: 'Option3' },
  { mainGroup: '', label: 'My Option4', value: 'Option4' },
  { mainGroup: '', label: 'My Option5', value: 'Option5' },
  { mainGroup: '', label: 'My Option6', value: 'Option6' },
  { mainGroup: '', label: 'My Option7', value: 'Option7' },
]

From the above data, I am rendering options in the select box using the below code:

<select>   
<option value=''>Please select</option>
{myDaya .map((option: { mainGroup:string; value: string; label: string }) => (
<optgroup label={option.mainGroup}>
    <option key={option.value} value={option.value}>
    {option.label}
    </option>
</optgroup>
))}
</select>

From the above code, the select box looks like this:

enter image description here

But I want to show Group1 Option1, Group1 Option2, and Group1 Option3 under Group1 & for other options mainGroup is blank so it should not show blank space in Select-box.

0

There are 0 best solutions below