React: Tabs with lifted state

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 }): a button with role="tab", aria-selected set to isActive, and the class active only when it is active.
  • App renders the three buttons inside a div with role="tablist", then a div with role="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>
  );
}

Lesson: Sharing state between components →