Controlled HTML select element in React has weird default UX

submited by
Style Pass
2021-06-25 20:00:09

And to make things more confusing (if you as a developer know that it only looks like Ford is selected), you open the dropdown and select Ford again, the onChange handler is not going to get called. I am not sure exactly why that happens but it points at the UI and React state being out of sync.

The right situation for a select element is that it should always have a valid value. There are two ways I can think of dealing with this: 1) hope every caller of Select picks a valid initial value or 2) use an effect to trigger the passed in onChange with a valid default value. Here's what the latter could look like.

This technique is what I ended up using in DataStation. The effect is only ever called once to initialize the value. It gets rid of all the out-of-sync weirdness if a blank value is passed in.

The only thing I'm not sure of is that children is not included in the list of the effect's dependencies. I assume React takes care of re-rendering the entire component if children change but I am not sure.

Leave a Comment