Search code examples
reactjsreact-hook-formreactstrap

Uncaught TypeError: fieldRef.focus is not a function error in React-hook-form setFocus with Reactstrap Input


I'm using react-hook-form to manage my form. I want my interface to scroll to the first error field on error submit but I'm getting this error every single time I use setFocus enter image description here

This is my controller code

<Controller
    name="first_name"
    control={control}
    render={({ field: { ref, ...field } }) => (
      <Input
           {...field}
           innerRef={ref}
           type="text"
           id="first_name"
           className={classnames({
              'input-error': formState?.errors?.first_name?.message,
           })}
           autoComplete="nope"
        />
    )}
/>

and this is my setFocus code block

useEffect(() => {
    const firstError = (Object.keys(errors) as Array<keyof typeof errors>).reduce<keyof typeof errors | null>((field, a) => {
      const fieldKey = field as keyof typeof errors;
      return !!errors[fieldKey] ? fieldKey : a;
    }, null);

    console.log({ firstError });

    if (firstError) {
      setFocus(firstError);
    }
  }, [errors]);

I somehow managed to create a sandbox for it but it doesn't show the same error. It errors on exact same code though. https://codesandbox.io/s/gallant-voice-vqqi47?file=/src/App.js


Solution

  • If you ever encounter this error, this was caused by React's Strict Mode in dev environment. It means that this error wont occur on live environment. If you want to test your code without this error, just temporarily remove the strict mode.

    Refer to this thread here