Categories
React Answers

How to store the state of radio groups in React using react-hook-form?

Spread the love

Sometimes, we want to store the state of radio groups in React using react-hook-form.

In this article, we’ll look at how to store the state of radio groups in React using react-hook-form.

How to store the state of radio groups in React using react-hook-form?

To store the state of radio groups in React using react-hook-form, we can set the defaultChecked prop to the initial checked value for each radio button.

For instance, we write:

import React, { useState } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const [state] = useState({ data: { checked: "1" } });
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="vehicles">
        How many vehicles do you own?
        <br />
        <input
          type="radio"
          name="vehicles"
          value="1"
          {...register("vehicles", { required: true })}
          className="radio"
          defaultChecked={state.data.checked === "1"}
        />
        <label>1</label>
        <input
          type="radio"
          name="vehicles"
          value="2"
          {...register("vehicles", { required: true })}
          className="radio"
          defaultChecked={state.data.checked === "2"}
        />
        <label>2</label>
        {errors.vehicles && (
          <div className="form_error">Number of Vehicles is required</div>
        )}
      </label>

      <input type="submit" />
    </form>
  );
}

We use the useForm hook to return an object with various properties we use to create our form.

Next, we define the onSubmit function that we use as the form submit handler.

Then we add our form element with the onSubmit prop set to handleSubmit(onSubmit) which only runs when the form values are all valid.

Next, we add inputs that we register as react-hook-form fields with register.

And we set the defaultChecked prop to set the condition for which the radio button is checked.

The initial checked value is checked according to the initial state value.

Therefore, 1 should be selected initially.

Conclusion

To store the state of radio groups in React using react-hook-form, we can set the defaultChecked prop to the initial checked value for each radio button.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *