Skip to content

Instantly share code, notes, and snippets.

@dipeshhkc
Last active June 10, 2021 09:19
Show Gist options
  • Save dipeshhkc/d4704ce2852bc6194c44e938595a564a to your computer and use it in GitHub Desktop.
Save dipeshhkc/d4704ce2852bc6194c44e938595a564a to your computer and use it in GitHub Desktop.
Scroll To the First Error Element [FORMIK]
//(1/3) Snippet to getting first error(works even if nested case)
import { isObject } from "lodash";
export const getFirstErrorKey = (object: any, keys: string[] = []): any => {
let firstErrorKey = "";
if (Array.isArray(object)) {
for (let i = 0; i < object.length; i++) {
if (object[i]) {
firstErrorKey = Object.keys(object)[i];
break;
}
}
} else {
firstErrorKey = Object.keys(object)[0];
}
if (firstErrorKey && isObject(object[firstErrorKey])) {
return getFirstErrorKey(object[firstErrorKey], [...keys, firstErrorKey]);
}
return [...keys, firstErrorKey].join(".");
};
//(2/3) Snippet to focus to that error input
import { getFirstErrorKey } from "./getFirstErrorKey";
export const focusElement = (errors: any) => {
let element = null;
const firstErrorKey = getFirstErrorKey(errors);
if (global.window.document.getElementsByName(firstErrorKey).length) {
element = global.window.document.getElementsByName(firstErrorKey)[0];
if (element instanceof HTMLInputElement) {
element.focus();
} else {
element = element.getElementsByTagName("input")[0];
if (element instanceof HTMLInputElement) {
element.focus();
}
}
}
};
//(3/3) Final Usage
useEffect(() => {
if (!isValid && submitCount > 0) {
focusElement(errors);
}
}, [submitCount, isValid]);
@bibek-magar
Copy link

πŸ™‡ πŸš€

@dipeshdulal
Copy link

πŸš€ πŸ™‡ 😍 🀩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment