0

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 !

8
  • your codesandbox not working Commented Jul 10, 2022 at 11:00
  • you sure? check again please Commented Jul 10, 2022 at 11:02
  • yes, sure, it show default App of codesandbox Commented Jul 10, 2022 at 11:03
  • 1
    okey I think now it should be fixed Commented Jul 10, 2022 at 11:07
  • 1
    If I do that, then I'm selecting both of the radio inputs and can't unselect either of them. check the sandbox Commented Jul 10, 2022 at 11:17

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.