Search code examples
reactjsredux-formreact-final-form

React-final-form focus doesn't focus on given field


I was trying to focus on the field when the user press the button, I used focus('fieldName'), but it seems doesn't work.

Below is codesandbox: https://codesandbox.io/s/condescending-heisenberg-q8dcr?file=/src/App.jsx


Solution

  • As @erikras responded in GitHub issue:

    That's not what form.focus() does. form.focus() tells Final Form that a field has received focus.

    You need an actual ref to the DOM node. Like this: https://codesandbox.io/s/mystifying-mestorf-26yv8?file=/src/App.jsx

    From codesandbox, we should const ref = useRef(); with Input

    <Field name="firstName" type="text">
              {({ input }) => (
                <input {...input} placeholder="First Name" ref={ref} />
              )}
    </Field>
    

    Then onClick:

        <button
          type="button"
          onClick={() => {
            ref.current.focus();
          }}
          disabled={submitting || pristine}
        >
          Focus
        </button>