DEV Community

NDREAN
NDREAN

Posted on • Edited 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 (
    <>
      <input
        type="radio"
        name={name}
        value={value}
        id={id}
        onChange={handleChange}
      />
      <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(e.target.name, {
        val: e.target.value,
        id: e.target.id
      })
    );
  }
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 />

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

Top comments (0)