Skip to content

Commit

Permalink
focusing drawer toggle only when drawer goes from open to close (#1590)
Browse files Browse the repository at this point in the history
  • Loading branch information
scheul93 authored and pwolfert committed Feb 15, 2022
1 parent 8b322ec commit 0d00ce2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<DrawerToggle {...defaultProps} drawerOpen={false}>
Expand All @@ -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);
});
});
Original file line number Diff line number Diff line change
@@ -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 & {
/**
Expand Down Expand Up @@ -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]);
Expand Down
13 changes: 13 additions & 0 deletions packages/design-system/src/components/Drawer/usePrevious.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(value: T): T | undefined => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
};

export default usePrevious;

0 comments on commit 0d00ce2

Please sign in to comment.