reactjsmaterial-uireact-hook-form

cant setfocus multiple fields mui react hook form


Go to '...' https://codesandbox.io/p/sandbox/jc2vtn

Type some value into the top fields (street1, street2, city).

Then click the "Same as billing" checkbox. This checkbox's onChange event copies the values from the top fields into the bottom fields.

But, setFocus does not work properly. If I use setFocus on the three fields separately (when checking if they have a value or not), setFocus works only for the last field called.


Solution

  • setFocus will move the cursor to the field you input into the function. It doesn't do anything if you try and do it to multiple fields at once. I think your goal is to fix the label overlap issue? I found this happened to me when the component change from uncontrolled (ie has an undefined as the value) to controlled (has a value). Try setting the value of the field like this so it's always controlled:

    <TextField
       value={value ?? ""}
       ...
    />
    

    I would also recommend using the React Hook Form Controller when you want to combine it with Mui components. https://react-hook-form.com/docs/usecontroller/controller See also React Material UI Label Overlaps with Text