zt1983811
zt1983811

Reputation: 1017

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

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

Upvotes: 4

Views: 2708

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

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.

Upvotes: 4

Related Questions