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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more