+
+
-
{children}
diff --git a/lib/focus-trap.tsx b/lib/focus-trap.tsx
index 048ba2b9a..b3ab38006 100644
--- a/lib/focus-trap.tsx
+++ b/lib/focus-trap.tsx
@@ -10,22 +10,40 @@ export default function FocusTrap({ children }: Props) {
const anchor: RefObject
= React.useRef(document.activeElement)
const returnFocus = () => {
+ // Returns focus to the last focused element prior to trap.
if (anchor) {
anchor.current.focus()
}
}
const trapFocus = () => {
- const focusableElements = tabbable(root.current)
+ if (root.current) {
+ root.current.focus()
+ selectFirstFocusableEl()
+ }
+ }
- if (focusableElements[0]) {
- focusableElements[0].focus()
+ const selectFirstFocusableEl = () => {
+ // Try to find focusable elements, if match then focus.
+ let match = null
+ let end = 10 // Try to find match at least 10 times.
+ let i = 0
+
+ while (!match !== i > end) {
+ console.log('-----------', i)
+ match = !!tabbable(root.current).length
+ if (match) {
+ tabbable(root.current)[0].focus()
+ }
+ i = i + 1
}
}
useEffect(() => {
setTimeout(trapFocus, 20)
- return returnFocus
+ return () => {
+ returnFocus()
+ }
}, [root, children])
return React.createElement('div', {