I have a select dropdown menu that is split by optgroups. For my on change function I also want to record which optgroup the option was picked from. The options are dynamically rendered. I can easily get the value of the selected option but I have no idea how to record the optgroup as well.
Essentially I would love to have a way to have both the option value (e.target.value) and the name of the optgroup it came from to use in a onChange function.
<div className="">
<select
onChange={(e) => {
console.log(e.target);
}}
className=" bg-gray-500"
>
<option>Pick Player</option>
<optgroup label="Substitutes">{subOptions}</optgroup>
<optgroup label="Reserves"></optgroup>
{reserveOptions}
<optgroup label="First Team"></optgroup>
{firstTeamOptions}
<optgroup label=""></optgroup>
<option>+ Add Player</option>
</select>
</div>
The trick is to get the selected
<option>element usinge.currentTarget.options[e.currentTarget.selectedIndex]. Once you have access to the selected option element:.valueto access its value, and.closest('opt group')?.labelto access the label of its closest<optgroup>parent. The optional chaining operator will take into account the scenario where the option is not nested inside an<optgroup>.Proof-of-concept below using JS, but you can easily abstract the logic to the React component's
onChangehandler: