Linked Questions

Popular Questions

I am trying to create a component in my form that uses two buttons to increment and decrement the value of a input field. However, I cannot get react-hook-form to register the value properly.

Here is what it looks like: How it looks like

At first I tried the following code:

const Incrementor = ({ label, error, register }: IIncrementorProps) => {
    const [number, setNumber] = useState(0);

    return (
        <>
            <label className='label'>{ label }</label>
            <div className=''>
                <button type='button' onClick={ () => {setNumber(number + 1)} }>+</button>
                <div className='control'>
                    <input className='incrementor-display' type='text' value={ number } onChange={ (e) => {console.log(e)} } />
                </div>
                <button type='button' onClick={ () => {setNumber(number - 1)} }>-</button>
            </div>
            {error && <span className='help'>This field is required</span>}
        </>
    );
}

However, the form would not register the correct value in the input value (instead registering the value at the very beginning after a resubmit). I thought this was due to it not registering a change event so I tried the following code:

const Incrementor = ({ label, error, register }: IIncrementorProps) => {
    const [number, setNumber] = useState(0);
    let inputElement:HTMLInputElement | null;

    const handleClick = (changeAmount: number) => {
        setNumber(number + changeAmount);
        var event = new Event('change', { bubbles: true });
        inputElement?.dispatchEvent(event);
    }

    return (
        <>
            <label className='label'>{ label }</label>
            <div className=''>
                <button type='button' onClick={ () => {handleClick(1)} }>+</button>
                <div className='control'>
                    <input className='incrementor-display' type='text' value={ number } onChange={ (e) => {console.log(e)} } ref={(input) => inputElement = input} />
                </div>
                <button type='button' onClick={ () => {handleClick(-1)} }>-</button>
            </div>
            {error && <span className='help'>This field is required</span>}
        </>
    );
}

Still, no change event is registering and now the form is not getting any value at all (an error is triggered). How do I fix this? Here is how I'm using the component btw:

<Incrementor label={ entry.label } error={ errors[entry.id] } register={ register(entry.id, {required: true}) }/>

Related Questions