diff --git a/packages/eds-core-react/src/components/Tabs/Tabs.tsx b/packages/eds-core-react/src/components/Tabs/Tabs.tsx index 53a1b9546e..f92c0ceccc 100644 --- a/packages/eds-core-react/src/components/Tabs/Tabs.tsx +++ b/packages/eds-core-react/src/components/Tabs/Tabs.tsx @@ -1,8 +1,8 @@ -import { forwardRef, useState, HTMLAttributes } from 'react' +import { forwardRef, useState, HTMLAttributes, useEffect, useRef } from 'react' import { TabsProvider } from './Tabs.context' import { Variants } from './Tabs.types' import { token as tabsToken } from './Tabs.tokens' -import { useId, useToken } from '@equinor/eds-utils' +import { useId, useToken, useCombinedRefs } from '@equinor/eds-utils' import { ThemeProvider } from 'styled-components' import { useEds } from '../EdsProvider' @@ -28,8 +28,10 @@ const Tabs = forwardRef(function Tabs( ref, ) { const tabsId = useId(id, 'tabs') - + const tabsRef = useRef(null) + const combinedTabsRef = useCombinedRefs(tabsRef, ref) const [tabsFocused, setTabsFocused] = useState(false) + const [listenerAttached, setListenerAttached] = useState(false) let blurTimer @@ -48,17 +50,30 @@ const Tabs = forwardRef(function Tabs( } clearTimeout(blurTimer) - //Only force focus on active Tab if Tabs was navigated to with keyboard - const checkIfTabWasPressed = (event: KeyboardEvent) => { - document.removeEventListener('keyup', checkIfTabWasPressed, true) - if (event.key === 'Tab') setTabsFocused(true) + if (tabsFocused) return + if (!listenerAttached) { + setListenerAttached(true) + tabsRef.current.addEventListener('keyup', checkIfTabWasPressed, { + once: true, + }) } - if (!tabsFocused) - document.addEventListener('keyup', checkIfTabWasPressed, true) - onFocus && onFocus(e) } + //Only force focus on active Tab if Tabs was navigated to with keyboard + const checkIfTabWasPressed = (event: KeyboardEvent) => { + setListenerAttached(false) + if (event.key === 'Tab') setTabsFocused(true) + } + + useEffect(() => { + const tabs = tabsRef.current + return () => { + if (tabs) tabs.removeEventListener('keyup', checkIfTabWasPressed) + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + const { density } = useEds() const token = useToken({ density }, tabsToken) @@ -73,7 +88,12 @@ const Tabs = forwardRef(function Tabs( tabsFocused, }} > -
+
)