Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-hook-form with Material-ui textfield without autoFocus defaultValue disappeared during form submit

I have problem using react-hook-form v7 + material-ui textfield. The defaultValue working if I set autoFocus or I manually change the textfield value. However if I just submit without mouse click on the filed that not autoFocus, the defaultValue disappeared during the form submit. Please check codesandbox link

  • Test 1: don't touch anything, click submit, you will see submit value only has title but missing name and desc result

  • Test 2: mouse click or change value in name, you will see after submit the value of name is there enter image description here

My question is how to make this default value always submit even though without mouse click or change the value of the textField?

Please help and thanks in advance

like image 644
zt1983811 Avatar asked Oct 27 '25 12:10

zt1983811


1 Answers

To use Material-ui with react-hook-form. It is better to wrap it with Controller to allow react-hook-form to link with the 3rd party library element.

https://react-hook-form.com/api/usecontroller/controller

Wrap Textfield with Controller

const { handleSubmit, control } = useForm();
...

<Controller
    render={({ field }) => (
    <TextField
        autoFocus
        margin="dense"
        id="title"
        label="Title"
        type="text"
        fullWidth
        {...field}
    />
    )}
    control={control}
    name="title"
    defaultValue={data.title}
/>
...

After that, the default value will be able to work as expected.

Here is the codesandbox for demo.

like image 168
Mic Fung Avatar answered Oct 30 '25 01:10

Mic Fung