Last active
June 10, 2021 09:19
-
-
Save dipeshhkc/d4704ce2852bc6194c44e938595a564a to your computer and use it in GitHub Desktop.
Scroll To the First Error Element [FORMIK]
This file contains hidden or 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
//(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]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
π π