I have a select menu with dynamic options. Something like this:
<select>
{options}
</select>
On page load I fetch the user’s current country and render this:
<select>
<option value="italy">Italy</option>
</select>
When the select-element is focused, I fetch all available countries:
(I’m not fetching it together with current country to reduce page loading time)
<select>
<option value="england">England</option>
<option value="france">France</option>
<option value="denmark">Denmark</option>
<option value="spain">Spain</option>
<option value="germany">Germany</option>
<option value="italy">Italy</option>
</select>
Problem
If the dropdown menu is open while the options get swapped out, the highlight will stay on the same position (selectedIndex doesn’t update according to the new value="italy" position)



How to reproduce
- Go to this Codesandbox
- Click on the select menu
- Observe
Desired result
I want the highlight to move to the ‘Italy’ option after option swap.
Attempts
I tried modifying the selectedIndex:
useEffect(() => {
if (optionsAreLoaded) {
selectRef.current.selectedIndex = 6
}
}, [options]);
But that didn’t do anything to the highlight
I also saw this similar question. In it, the OP answered themselves saying they had to reset the select value whenever the option list changed. So I tried this:
useEffect(() => {
setSelectedOption({ id: undefined, value: "", label: "" });
}, [options]);
But again, no effect to the highlight.
Question
Can I update the highlight position while the menu is open?
Do I maybe need to build my own select menu from scratch or use a library (React-select/Mantine/etc.)?
