Skip to content

Commit

Permalink
fix: Do not always refocus tab if rerender happens
Browse files Browse the repository at this point in the history
  • Loading branch information
danez committed Mar 31, 2022
1 parent 85caf7a commit 4c63bcb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 10 deletions.
17 changes: 7 additions & 10 deletions src/components/Tab.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -61,6 +52,12 @@ const Tab = (props) => {
...attributes
} = props;

useEffect(() => {
if (selected && focus) {
nodeRef.current.focus();
}
}, [selected, focus]);

return (
<li
{...attributes}
Expand Down
34 changes: 34 additions & 0 deletions src/components/__tests__/Tabs-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,40 @@ describe('<Tabs />', () => {
assertTabSelected(2);
});

test('should not focus tab again on rerender', () => {
const { rerender } = render(
<>
<input data-testid="input1" />
{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(
<>
<input data-testid="input1" />
{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({
Expand Down

0 comments on commit 4c63bcb

Please sign in to comment.