Created
September 20, 2022 11:05
-
-
Save hereisfahad/0f3f89c94cd71757ad05f1a7d96683b8 to your computer and use it in GitHub Desktop.
Focus first error, formik, reactjs, dom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add custom attribute on the input element or wrapper div data-valid={`${error ? "false" : "true"}} | |
import { useEffect } from 'react'; | |
import { useFormikContext } from 'formik'; | |
const FocusError = () => { | |
const { errors, isSubmitting, isValidating } = useFormikContext(); | |
useEffect(() => { | |
if (Object.keys(errors).length > 0 && isSubmitting && !isValidating) { | |
const firstErrorElement = document.querySelector('[data-valid="false"]'); | |
if (firstErrorElement) { | |
const position = firstErrorElement.getBoundingClientRect(); | |
// scrolls to 70px above element to eliminate navbar | |
window.scrollTo({ left: position.left, top: position.top + window.scrollY - 70, behavior: 'smooth' }); | |
} | |
} | |
}, [errors, isSubmitting, isValidating]); | |
return null; | |
}; | |
export default FocusError; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment