← All tasksReact · Middle
Tabs
Write a Tabs component that receives an array tabs of { label, content } objects. Each tab gets a button with role="tab" and the label text; below the buttons, only the active tab's content is shown.
The first tab is active initially. The active button has aria-selected="true", the others "false". An empty array renders no tabs and no errors.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (3)
const tabs = [{ label: 'A', content: 'Content A' }, { label: 'B', content: 'Content B' }, { label: 'C', content: 'Content C' }]; render(<Tabs tabs={tabs} />); expect(screen.getAllByRole('tab')).toHaveLength(3); expect(screen.getByRole('tab', { name: 'A' }).getAttribute('aria-selected')).toBe('true'); expect(screen.getByText('Content A')).toBeTruthy(); expect(screen.queryByText('Content B')).toBe(null);
const tabs = [{ label: 'A', content: 'Content A' }, { label: 'B', content: 'Content B' }]; render(<Tabs tabs={tabs} />); fireEvent.click(screen.getByRole('tab', { name: 'B' })); expect(screen.getByText('Content B')).toBeTruthy(); expect(screen.queryByText('Content A')).toBe(null); expect(screen.getByRole('tab', { name: 'B' }).getAttribute('aria-selected')).toBe('true'); expect(screen.getByRole('tab', { name: 'A' }).getAttribute('aria-selected')).toBe('false');
render(<Tabs tabs={[]} />); expect(screen.queryAllByRole('tab')).toHaveLength(0);