DEV Community


Posted on • Updated on

TIL: use Maps with React radio inputs

An interesting usage of the object Map with React is when you use input elements of type radio. When you use a Map in your local state, it is enough to set the key as the group name, and its value can be the input value or an object (e.g. the value and the id). The Map acts as a set, so you are assured to have the image of the DOM in our Map, no further ado.

Let's take an example.

We build an input element of type "radio": the "name" attribute will group together theses inputs.

function Input({ name, value, id, handleChange }) {
  return (
      <label htmlFor={id}>{id}</label>
Enter fullscreen mode Exit fullscreen mode

We setup two groups - named "gp1" and "gp2" of two radio inputs. We display the group name, the key and the value. On change, we update the state with a new Map - based on the old one - where the key is the group name, and the value is an object {value, id} here. We now have the image of the DOM in our Map.

export default function App() {
  const [radio, setRadio] = useState(new Map());

  function handleChange(e) {
    return setRadio((radio) =>
      new Map(radio).set(, {
return (
    <div className="App">
      <Input name="gp1" value={1} id="one" handleChange={handleChange} />
      <Input name="gp1" value={2} id="two" handleChange={handleChange} /> |{" "}
      <Input name="gp2" value={3} id="three" handleChange={handleChange} />
      <Input name="gp2" value={4} id="four" handleChange={handleChange} />
      <hr />

      {[].map((k, i) => (
        <p key={i}>
          group: {k}, {radio.get(k).id}: {radio.get(k).val}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)