I have a registration form in my project with several inputs. I'm getting the values of those inputs and sending them to a server with a post request method. I've managed to most of the functionality correctly, though I'm struggling a little bit with the type radio input. Basically, I have a simple yes or no radio input, If the user clicks on the "yes" radio input, I want the state to be updated as true, if they select "no", then as false. I need to have the value in one state because that's how I'm passing it in the post method, so the state changes depending on the user answer. I have made a simple example of that in codesandbox. As you can see, I have a simple form with two radio type inputs, one yes and one no and I'm logging the data using react-hook-form's handleSubmit method. I'm setting the state as "true" when the "yes" input changes, so when the user clicks it and "false" when the user clicks on "no", however, when I'm logging the data, when I click on either one of those radio inputs, the state is always going to be set as "false", even If I'm clicking on "yes" radio input and I have no idea why, since I'm setting it as "true" on change. I'd appreciate any help, thank you !
CodePudding user response:
Its because you set value of both inputs is same value (question state), so change each value to "true" and "false" and it should work
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="field-rain">
<input
{...register('question')}
value="true"
type="radio"
name="question"
id="yes"
/>
Yes
</label>
<label htmlFor="field-wind">
<input {...register('question')} value="false" type="radio" id="no" />
No
</label>
<button type="submit">Submit</button>
</form>
</div>
you can check in codesandbox. Hope it help!