Home > OS >  Radio buttons with react-hook-form validation
Radio buttons with react-hook-form validation

Time:12-05

I have created a form having radio button and done validation with react hook form but while showing log data in console it shows always "on" on selection radio button.

<div className="">
              <label htmlFor="" className=" ">
                US Citizen?
              </label>
              <div className="">
                <div className="radio-container">
                  <input type="radio" name="radio" {...register("usCitizen")} />
                  <label>Yes</label>
                </div>

                <div className="radio-container">
                  <input type="radio" name="radio" {...register("usCitizen")} />
                  <label>No</label>
                </div>
              </div>
            </div>

CodePudding user response:

I think you need to add a function that handles the onclick event and also add a useState that can set the value to true or false Im not sure about the syntax but it pretty much like this:

const [radio, setRadio] = useState(false);

function handleClick(event){
    const [val] = event.target.value;

    setRadio(()=>{
    if (val === true){
       return(false)
    }
    else{
    return(true)
    }
}

}
<input type="radio" onclick={handleClick} value={radio}> 

CodePudding user response:

Use submit input type. (handleSubmit)

<form onSubmit={handleSubmit(onSubmit)}>
                <div className="">
                    <label htmlFor="" className=" ">US Citizen?</label>
                        <div className="">
                            <div className="radio-container">
                                <input type="radio" name="radio" value="yes" {...register("usCitizen")} />
                           <label>Yes</label>
                        </div>
        
                        <div className="radio-container">
                          <input type="radio" name="radio" value="no" {...register("usCitizen")} />
                          <label>No</label>
                        </div>
                      </div>
                    </div>
       <input type="submit" value="Submit" />
</form>
  • Related