Last active
November 20, 2023 07:23
-
-
Save yushanwebdev/4d6ca16c3420b28c194d5af245c24d57 to your computer and use it in GitHub Desktop.
Hook to manage the focus of the form and its children when they are invalid. (Inspired by Kent's suggestion in the focus management lesson in the Epic Web second workshop.)
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
export function useFocusInvalid( | |
formRef: HTMLFormElement | null, | |
hasErrors: boolean, | |
) { | |
useEffect(() => { | |
if (!formRef || !hasErrors) return | |
if (formRef.matches('[aria-invalid="true"]')) { | |
formRef.focus() | |
} else { | |
const invalidElementFirst = formRef.querySelector('[aria-invalid="true"]') | |
if (invalidElementFirst instanceof HTMLElement) { | |
invalidElementFirst.focus() | |
} | |
} | |
}, [formRef, hasErrors]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment