Skip to content

Commit

Permalink
Simplify selected tab logic + add a test
Browse files Browse the repository at this point in the history
- a basic fallback to `tabs[0]` suffices for this edge case and doesn't require extra logic/processing

- add a unit test to confirm the expected/desired behavior
  • Loading branch information
cee-chen committed Apr 29, 2024
1 parent de1de28 commit 7bb4136
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
27 changes: 27 additions & 0 deletions src/components/tabs/tabbed_content/tabbed_content.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -121,5 +121,32 @@ describe('EuiTabbedContent', () => {
);
expect(getAllByRole('tab')[1]).toHaveAttribute('aria-selected', 'true');
});

it('resets the selected tab to the first if the `tabs` content completely changes', () => {
const { rerender, getAllByRole, getByTestSubject } = render(
<EuiTabbedContent tabs={tabs} />
);

fireEvent.click(getByTestSubject('kibanaTab'));
expect(getAllByRole('tab')[1]).toHaveAttribute('aria-selected', 'true');

rerender(
<EuiTabbedContent
tabs={[
{
id: 'hello',
name: 'New tab 1',
content: <p>Hello</p>,
},
{
id: 'world',
name: 'New tab 2',
content: <p>World</p>,
},
]}
/>
);
expect(getAllByRole('tab')[0]).toHaveAttribute('aria-selected', 'true');
});
});
});
18 changes: 3 additions & 15 deletions src/components/tabs/tabbed_content/tabbed_content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,6 @@ export class EuiTabbedContent extends Component<
}
};

static getDerivedStateFromProps(
nextProps: EuiTabbedContentProps,
currentState: EuiTabbedContentState
) {
if (!nextProps.tabs?.find((tab) => tab.id === currentState.selectedTabId)) {
return {
...currentState,
selectedTabId: nextProps?.tabs[0]?.id,
};
}
return null;
}

render() {
const {
className,
Expand All @@ -168,9 +155,10 @@ export class EuiTabbedContent extends Component<
externalSelectedTab ||
tabs.find(
(tab: EuiTabbedContentTab) => tab.id === this.state.selectedTabId
);
) ||
tabs[0]; // Fall back to the first tab if a selected tab can't be found

const { content: selectedTabContent, id: selectedTabId } = selectedTab!;
const { content: selectedTabContent, id: selectedTabId } = selectedTab;

return (
<div className={className} {...rest}>
Expand Down

0 comments on commit 7bb4136

Please sign in to comment.