diff --git a/packages/design-system/src/components/Drawer/DrawerToggle.test.tsx b/packages/design-system/src/components/Drawer/DrawerToggle.test.tsx index 40ad9e467b..dfe5066d01 100644 --- a/packages/design-system/src/components/Drawer/DrawerToggle.test.tsx +++ b/packages/design-system/src/components/Drawer/DrawerToggle.test.tsx @@ -53,7 +53,7 @@ describe('DrawerToggle', () => { expect(toggle.getAttribute('aria-label')).toBe(ariaLabel); }); - it('focuses button when drawer is closed', () => { + it('focuses button when drawer goes from open to closed', () => { const { rerender } = renderDrawerToggle({ drawerOpen: true }); rerender( @@ -63,4 +63,10 @@ describe('DrawerToggle', () => { const toggle = screen.getByRole('button'); expect(toggle).toEqual(document.activeElement); }); + + it('does not focus button when drawer in initialized to close', () => { + renderDrawerToggle({ drawerOpen: false }); + const toggle = screen.getByRole('button'); + expect(toggle).not.toEqual(document.activeElement); + }); }); diff --git a/packages/design-system/src/components/Drawer/DrawerToggle.tsx b/packages/design-system/src/components/Drawer/DrawerToggle.tsx index 587395df44..cff5de15da 100644 --- a/packages/design-system/src/components/Drawer/DrawerToggle.tsx +++ b/packages/design-system/src/components/Drawer/DrawerToggle.tsx @@ -1,6 +1,7 @@ import Button, { ButtonProps } from '../Button/Button'; import React, { useEffect, useRef } from 'react'; import classNames from 'classnames'; +import usePrevious from './usePrevious'; export type DrawerToggleProps = ButtonProps & { /** @@ -39,9 +40,11 @@ export const DrawerToggle = ({ ...others }: DrawerToggleProps): React.ReactElement => { const buttonRef = useRef(null); + const prevDrawerOpenProp = usePrevious(drawerOpen); useEffect(() => { - if (!drawerOpen && buttonRef.current) { + // if drawer was open but now closed, focus the toggle + if (prevDrawerOpenProp && !drawerOpen && buttonRef.current) { buttonRef.current.focus(); } }, [drawerOpen]); diff --git a/packages/design-system/src/components/Drawer/usePrevious.ts b/packages/design-system/src/components/Drawer/usePrevious.ts new file mode 100644 index 0000000000..be30846604 --- /dev/null +++ b/packages/design-system/src/components/Drawer/usePrevious.ts @@ -0,0 +1,13 @@ +import { useEffect, useRef } from 'react'; + +// storing a previous version of a prop for comparison +// similar to the old previousProps param from `componentDidUpdate` +const usePrevious = (value: T): T | undefined => { + const ref = useRef(); + useEffect(() => { + ref.current = value; + }); + return ref.current; +}; + +export default usePrevious;