Is it possible to get react-hook-form defaultValue updating with state?

Viewed 728

I would like to auto-fill a text field based on the selection made in a dropdown, I thought that the state change would cause the form to re-render and thus create the desired effect, however this is not the case.

Here is the minimum working example that demonstrates my problem.

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

function FormTest (){
    const [dropdownValue, setDropdownValue] = React.useState('Option 1');

    const { register, handleSubmit } = useForm({
        defaultValues: {
            textfield: dropdownValue,
        },
        mode: 'onChange'
    },);

    const onSubmit = (form) => {
        alert(JSON.stringify(form))
    }

    return(
        <div>
            <form onSubmit={handleSubmit(onSubmit)}>
                <select name='dropdown'
                    ref={register}
                    value={dropdownValue}
                    onChange={(e) => setDropdownValue(e.currentTarget.value)}>
                        <option value="Option 1">Option 1</option>
                        <option value="Option 2">Option 2</option>
                </select>
                <input type='text'
                    name="textfield"
                    ref={register}
                />
                <input type='submit'/>
            </form>
        </div>

    );
}

export default FormTest;

When I change the dropdown from Option 1 to Option 2, dropdownValue is changed to Option 2 however, the text in the text field remains as Option 1. Is there a way to get this updating? Perhaps a forced re-render of the text field? Or is this not possible?

Thanks

1 Answers

You can use setValue from "react-hook-form":

const { register, handleSubmit, setValue } = useForm({ // setValue
  // ...
})

setValue will accept the name and the new value:

onChange={(e) => {
  setDropdownValue(e.currentTarget.value)
  setValue('textfield', e.currentTarget.value)
}}
Related