Skip to content

Instantly share code, notes, and snippets.

@yushanwebdev
Last active November 20, 2023 07:23
Show Gist options
  • Save yushanwebdev/4d6ca16c3420b28c194d5af245c24d57 to your computer and use it in GitHub Desktop.
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.)
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