Sunday, June 28, 2020

easy set of radio buttons in react

It's funny, a few basic elements are a bit tricky in pure-function React - but then again checkboxes  and radio buttons and select/options could be a bit of a semantic pain in JQuery too.

(One real pain was using setInterval - I can use the approach outlined here but it's kind of brittle, like it needs to be inside the render...)

Anyway, here is some quick and dirty code for making a set of radio buttons:
const RadioSet = ({ selectedVal, setter, valToCaptions }) => {
    return Object.keys(valToCaptions).map((val) => {
        const caption = valToCaptions[val];
        return (
            <label key={val}>
                <input onChange={() => setter(val)} type="radio" checked={val == selectedVal} />
                {caption}
            </label>
        );
    });
};
In my case selectedVal and setter are what I get from useState(), and valToCaptions is a just a simple object of key/val pairs. Nothing fancy but I stopped violating DRY with so many radio buttons...

No comments:

Post a Comment