final-form-focus icon indicating copy to clipboard operation
final-form-focus copied to clipboard

Provide custom focus implementation

Open likerRr opened this issue 6 years ago • 3 comments

feature request

It would be nice to specify focus implementation. For example to make smooth scroll to element + Npx above it before focusing:

import createDecorator from 'final-form-focus'

const onFocus = input => {
  const { top } = getOffset(input);
  const scrollTop = top - 50;

  window.scrollTo({
    top: scrollTop,
	behavior: 'smooth',
  });

  input.focus();
}

const focusOnErrors = createDecorator(null, null, onFocus)

likerRr avatar Aug 15 '19 11:08 likerRr

@erikras Any plans to support custom focus implementations?

AndyOGo avatar Feb 26 '20 09:02 AndyOGo

My team has rolled its own solution for this, which focuses on the input and smooth-scrolls to it using scrollIntoView. Therefore, we stopped using this library. Our solutions looks like this:

import React from 'react'
import { Form as FinalForm } from 'react-final-form'

const Form = props => (
  <FinalForm {...props}>
    {({
      form: finalFormApi,
      handleSubmit,
    }) => (
      <form
        finalFormApi={finalFormApi}
        {...props}
        onSubmit={event => {
          const invalidField = finalFormApi.getRegisteredFields().find(field => finalFormApi.getFieldState(field).invalid)

          if (invalidField) {
            const targetInput = document.querySelector(`[name="${invalidField}"]`)
            const targetLabel = document.querySelector(`label[for="${invalidField}"]`) || targetInput
            if (targetInput) {
              targetInput.focus({ preventScroll: true })
              targetLabel.scrollIntoView({
                behavior: 'smooth',
                block: 'center',
              })
            }
          }

          handleSubmit(event)
        }}
      >
        {props.children}
      </form>
    )}
  </FinalForm>
)

export default Form

mattrabe avatar Feb 27 '20 17:02 mattrabe

FYI, here's a PR for this: https://github.com/final-form/final-form-focus/pull/25

TheRusskiy avatar Apr 21 '21 07:04 TheRusskiy