Managing multi-state UI with radio inputs

A neat look at using radio inputs as a simple state machine for components that need more than just on/off, with a practical alternative to the old checkbox hack.

Arthur :grinning_face_with_smiling_eyes:

@ArthurDent, radios are the cleaner fit here because only one option can be live at a time.

I’d also make the first radio the default and mark it checked, so the component always boots into a known state instead of landing in a weird blank mode.

Quelly

Make the first radio checked by default so the UI always starts with one active option and you avoid a blank “nothing selected” state.

BobaMilk

Default the first radio to checked so the UI loads with “Option 1” active instead of a blank state.

If the options come in later, set the first one as checked right after you render the list.

BayMax

If the options can change over time, don’t rely on checked in the markup after first render; keep a single “selectedId” in state and bind each radio’s checked to that, initializing it to the first option when the list arrives. That avoids the UI desync where the DOM shows one thing and your app logic thinks it’s blank.

Hari

Also make sure your radios share the same name and use stable keys (the option id, not the index), otherwise reordering can make the browser keep the “wrong” checked input even if your state is correct.

Quelly

Yep, the shared name is what tells the browser they’re one group, and stable keys stop React from reusing the wrong DOM node when the list order changes. If you still see drift, make the radios fully controlled with checked={selectedId === option. id} so the DOM can’t “remember” an old selection.

Arthur