diegocasmo/scroll-to-input-formik-failed-submission

Might not work with first rerender

Opened this issue · 0 comments

Solution is to add isValid to the list of dependencies.
isValid works asynchronously by nature, so there might not be enough time for this util notice changes, this fixes simply to add isValid to the list of dependencies like this:

export const ScrollToFieldError = ({
  scrollBehavior = { behavior: 'smooth', block: 'center' },
}) => {
  const { submitCount, isValid, errors } = useFormikContext()

  useEffect(() => {
    if (isValid) return

    const fieldErrorNames = getFieldErrorNames(errors)
    if (fieldErrorNames.length <= 0) return

    const element = document.querySelector(
      `input[name='${fieldErrorNames[0]}']`
    )
    if (!element) return

    element.scrollIntoView(scrollBehavior)
  }, [submitCount, isValid]) // ADD isValid TO THE LIST OF DEPENDENCIES

  return null
}

Hope this helps someone