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!
To set the default checked value of a radio button in React:Store the radio button value in the state. Initialize the state to the value of the default checked radio button. Set the checked property on each radio button conditionally, e.g. checked={selected === 'yes'} .
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
While there's currently no React Hook that does this out of the box, you can manually retrieve either the previous state or props from within a functional component by leveraging the useRef , useState , usePrevious , and useEffect Hooks in React.
I think you are after this:
https://reactjs.org/docs/uncontrolled-components.html
<input type="radio" defaultChecked={state.data.checked === 'xxx'} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With