How do I store the state of radio groups in React using react-hook-form

Doomd picture Doomd · Jan 10, 2020 · Viewed 10k times · Source

I'm using react-hook-form to store form data that is split into two pages as per the code seen on Codesandbox.io. I am able to successfully store simple text inputs (like first name, email, etc) using property assignments like defaultValue={state.data.firstName} for example...but I can't figure out how to store the checked item in the radio group using the model suggested by react-hook-form. I've checked their documentation, and it's unfortunately sparse in mentioning radio button group state storage. Is this possible using their API?

import React from "react";
import { useForm } from "react-hook-form";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import updateAction from "./updateAction";

const Step1 = props => {
  const { register, handleSubmit, errors } = useForm();
  const { action, state } = useStateMachine(updateAction);
  const onSubit = data => {
    action(data);
    props.history.push("./step2");
  };

  return (
    <form onSubmit={handleSubmit(onSubit)}>
      <h2>Step 1</h2>
      <label>
        First Name:
        <input
          name="firstName"
          ref={register}
          defaultValue={state.data.firstName}
        />
      </label>
      <label>
        Last Name:
        <input
          name="lastName"
          ref={register}
          defaultValue={state.data.lastName}
        />
      </label>

      <label className="control-label" htmlFor="vehicles">How many vehicles do you own?<br />
        <input type="radio" name="vehicles" id="vehicles-1" value="1"
          ref={register({ required: true })} className="radio" />
        <label class="radio">1</label>

        <input type="radio" name="vehicles" id="vehicles-2" value="2"
          ref={register({ required: true })} className="radio" />
        <label class="radio">2</label>
        {errors.vehicles && <div className="form_error">Number of Vehicles is required</div>}
      </label>

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

export default withRouter(Step1);

Thanks, in advance, for your help!

Answer

Bill picture Bill · Jan 10, 2020

I think you are after this:

https://reactjs.org/docs/uncontrolled-components.html

<input type="radio" defaultChecked={state.data.checked === 'xxx'} />