4

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

1
  • Thanks for @micFung solution. The major problem of this one is material-ui and react-hook-form are using different keys inputRef vs ref. There are 2 solutions 1. use react form controller codesandbox.io/s/… 2. manually map inputRef and ref codesandbox.io/s/… Commented Jul 6, 2021 at 16:20

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @micFung , this is working solution. An extra, I would like to know if there is solution without using Controller ? just use register?
Yes you can. but you need to set the ref yourself explicitly because the input ref in material-ui is called inputRef instead of ref so the register() provided ref cannot be mapped correctly.
Here is the codesandbox for demo: codesandbox.io/s/…
Awesome, I see the problem now. Thanks so much. I wish material-ui or react-hook-form could make it computable one day :-) . Great answer and explanation @micFung

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.