Tabs are a set of buttons that must agree on which one is active.
What to build
A tab bar with three tabs and a panel showing the active tab's text.
Requirements
- Data:
Home(Welcome back!),Profile(Your details),Settings(Change your preferences). - Write
TabButton({ label, isActive, onSelect }): abuttonwithrole="tab",aria-selectedset to isActive, and the classactiveonly when it is active. Apprenders the three buttons inside adivwithrole="tablist", then adivwithrole="tabpanel"showing the active tab's text. The first tab starts active.
Constraints
Only App has state.
Example
Clicking Profile makes it the only active tab and the panel shows "Your details".
Why it works
One index in the parent decides which tab is active, so exactly one button can be selected at a time, and the panel always matches it.
Hints
Hint 1
App keeps the active tab's index; each TabButton gets isActive and onSelect.
Hint 2
role="tab" and aria-selected={isActive} make the buttons accessible tabs.
Solution
Show one correct solution (try it yourself first)
import { useState } from "react";
const TABS = [
{ label: "Home", text: "Welcome back!" },
{ label: "Profile", text: "Your details" },
{ label: "Settings", text: "Change your preferences" },
];
function TabButton({ label, isActive, onSelect }) {
return (
<button role="tab" aria-selected={isActive} className={isActive ? "active" : undefined} onClick={onSelect}>
{label}
</button>
);
}
export default function App() {
const [active, setActive] = useState(0);
return (
<div>
<div role="tablist">
{TABS.map((t, i) => (
<TabButton key={t.label} label={t.label} isActive={i === active} onSelect={() => setActive(i)} />
))}
</div>
<div role="tabpanel">{TABS[active].text}</div>
</div>
);
}