From 4c63bcb057f82de498bbb3325556f6d26064aa8e Mon Sep 17 00:00:00 2001 From: Daniel Tschinder <231804+danez@users.noreply.github.com> Date: Thu, 31 Mar 2022 17:18:16 +0000 Subject: [PATCH] fix: Do not always refocus tab if rerender happens --- src/components/Tab.js | 17 ++++++-------- src/components/__tests__/Tabs-test.js | 34 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/components/Tab.js b/src/components/Tab.js index 8c0c5dc67..5f8ad0c44 100644 --- a/src/components/Tab.js +++ b/src/components/Tab.js @@ -37,21 +37,12 @@ const propTypes = { const Tab = (props) => { let nodeRef = useRef(); - const checkFocus = () => { - const { selected, focus } = props; - if (selected && focus) { - nodeRef.current.focus(); - } - }; - useEffect(() => { - checkFocus(); - }); const { children, className, disabled, disabledClassName, - focus, // unused + focus, id, panelId, selected, @@ -61,6 +52,12 @@ const Tab = (props) => { ...attributes } = props; + useEffect(() => { + if (selected && focus) { + nodeRef.current.focus(); + } + }, [selected, focus]); + return (
  • ', () => { assertTabSelected(2); }); + test('should not focus tab again on rerender', () => { + const { rerender } = render( + <> + + {createTabs()} + , + ); + const firstTab = screen.getByTestId('tab1'); + const inputField = screen.getByTestId('input1'); + + expect(firstTab).not.toHaveFocus(); + expect(inputField).not.toHaveFocus(); + + userEvent.click(firstTab); + + expect(firstTab).toHaveFocus(); + expect(inputField).not.toHaveFocus(); + + userEvent.click(inputField); + + expect(firstTab).not.toHaveFocus(); + expect(inputField).toHaveFocus(); + + rerender( + <> + + {createTabs()} + , + ); + + expect(firstTab).not.toHaveFocus(); + expect(inputField).toHaveFocus(); + }); + test('should not change tabs when arrow up/down is pressed and disableUpDownKeys is passed', () => { render( createTabs({