From a78d667031fcc8fd20653f0fbf37b73bea9d21b3 Mon Sep 17 00:00:00 2001 From: Belen Curcio Date: Wed, 6 Jan 2021 12:05:24 -0300 Subject: [PATCH] Add support for n attempts for dynamic components --- lib/focus-trap.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/focus-trap.tsx b/lib/focus-trap.tsx index bb80c46f9..8ebfe420c 100644 --- a/lib/focus-trap.tsx +++ b/lib/focus-trap.tsx @@ -28,21 +28,23 @@ export default function FocusTrap({ children, focusFirst = false }: Props) { } const selectFirstFocusableEl = () => { - // Try to find focusable elements, if match then focus. + // Try to find focusable elements, if match then focus // Up to 4 seconds of load time threshold let match = false - let end = 22 // Try to find match at least n times. + let end = 22 // Try to find match at least n times let i = 0 const timer = setInterval( () => { console.log('-----------', i) if (!match !== i > end) { match = !!tabbable(root.current).length - if (root.current) { + if (match) { + // Attempt to focus the first el tabbable(root.current)[0].focus() } i = i + 1 } else { + // Clear interval after n attempts clearInterval(timer) } },