简体   繁体   中英

Radio buttons with react-hook-form validation

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>

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}> 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM