Skip to content

Instantly share code, notes, and snippets.

@hereisfahad
Created September 20, 2022 11:05
Show Gist options
  • Save hereisfahad/0f3f89c94cd71757ad05f1a7d96683b8 to your computer and use it in GitHub Desktop.
Save hereisfahad/0f3f89c94cd71757ad05f1a7d96683b8 to your computer and use it in GitHub Desktop.
Focus first error, formik, reactjs, dom
// 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