samedi 19 décembre 2020

React Form Hook - onChange with Checkbox using handleSubmit not working properly

Thanks in advance.

I'm trying to create a React form which updates a counter on checking (or unchecking) boxes without re-rendering on each checkbox click.

(Background info:- Form values = {one: "1", two: "2", three: "3" etc.)

I wish to achieve the following:-

  1. Create a counter which adds (or subtracts) the value of the checkbox (converted to Number).

  2. Dynamically display the current counter value.

  3. Once user is happy with choices, then submit form.

Unfortunately, I'm stuck at the first hurdle when testing onChange and handleSubmit.

I've tried using handleSubmit, watch and onChange but still experiencing problems.

Here's my code, with onChange event linked to first input only.

import React from 'react';
import {useForm} from 'react-hook-form'

function HookCounter(props) {

    const { register, handleSubmit } = useForm()

    const submitForm = (data) => {
        console.log(data)
    }

    const displayData = (data) => {
        console.log(data)
    }

    return (
        <div>
            <h3>Checkbox Counter</h3>

            <h4>Count Total : </h4>
            <form onSubmit={handleSubmit(submitForm)}>
                <div className="counter-input">   
                    <input onChange={handleSubmit(displayData)} ref={register} name="one" id="one"type="checkbox" value="1"/>
                    <label htmlFor="one">One</label>
                </div>
                <div className="counter-input">   
                    <input ref={register} name="two" id="two"type="checkbox" value="2"/>
                    <label htmlFor="two">Two</label>
                </div>
                <div className="counter-input">   
                    <input ref={register} name="three" id="three"type="checkbox" value="3"/>
                    <label htmlFor="three">Three</label>
                </div>
                <div className="counter-input">   
                    <input ref={register} name="four" id="four"type="checkbox" value="4"/>
                    <label htmlFor="four">Four</label>
                </div>
                <div className="buttons">
                    <button type="submit">Submit</button>
                    <button >Reset</button>
                </div>
            </form> 
        </div>
    );
}

export default HookCounter;

Problem:

When selecting the first (test) checkbox (i.e. "One", displayData works, however, it takes a second click for the checkbox to actually display the tick.

Same when I uncheck the box :- the UI always lags one 'event' behind.

Does anyone have any suggestions on how best to proceed ?

I suspect that I will need the useState / useEffect hooks somewhere but I'm not sure how to integrate with the Form hook.

Thanks again.




Aucun commentaire:

Enregistrer un commentaire