|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useEffect, useRef } from "react"; |
| 4 | +import { useFormikContext } from "formik"; |
| 5 | + |
| 6 | +// After a submit with errors, scroll + focus the first invalid field |
| 7 | +export function FormErrorFocus() { |
| 8 | + const { submitCount, errors, isSubmitting } = useFormikContext<any>(); |
| 9 | + const lastHandled = useRef(0); |
| 10 | + |
| 11 | + useEffect(() => { |
| 12 | + if (isSubmitting) return; |
| 13 | + if (submitCount <= 0 || submitCount === lastHandled.current) return; |
| 14 | + |
| 15 | + const keys = Object.keys(errors || {}); |
| 16 | + if (keys.length === 0) return; |
| 17 | + |
| 18 | + const timer = setTimeout(() => { |
| 19 | + try { |
| 20 | + let target: HTMLElement | null = null; |
| 21 | + |
| 22 | + // 1) Try by id, then data-testid |
| 23 | + for (const key of keys) { |
| 24 | + target = |
| 25 | + (document.getElementById(key) as HTMLElement | null) || |
| 26 | + (document.querySelector( |
| 27 | + `[data-testid="${key}"]` |
| 28 | + ) as HTMLElement | null); |
| 29 | + if (target) break; |
| 30 | + } |
| 31 | + |
| 32 | + // 2) Fallback: first element with matching name |
| 33 | + if (!target) { |
| 34 | + for (const key of keys) { |
| 35 | + const byName = document.getElementsByName(key); |
| 36 | + if (byName && byName.length > 0) { |
| 37 | + target = byName[0] as HTMLElement; |
| 38 | + break; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if (target) { |
| 44 | + target.scrollIntoView({ behavior: "smooth", block: "center" }); |
| 45 | + if (typeof (target as any).focus === "function") { |
| 46 | + (target as any).focus({ preventScroll: true }); |
| 47 | + } |
| 48 | + } |
| 49 | + } finally { |
| 50 | + lastHandled.current = submitCount; |
| 51 | + } |
| 52 | + }, 0); |
| 53 | + |
| 54 | + return () => clearTimeout(timer); |
| 55 | + }, [submitCount, errors, isSubmitting]); |
| 56 | + |
| 57 | + return null; |
| 58 | +} |
0 commit comments