Skip to main content
04

Tabs

Mediumreacta11ykeyboarduseId

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Build a Tabs component. App.js passes it a list of items, each with an id, a label and some content. Right now Tabs shows every panel at once.

jsx
<Tabs items={[{ id: 'html', label: 'HTML', content: '...' }, ...]} />

Requirements

  • Only one panel is visible at a time. The first tab is selected initially.
  • Clicking a tab shows its panel. The selected tab is highlighted (the CSS already styles aria-selected="true").
  • Two Tabs on the same page must not interfere with each other, including their element ids.

Accessibility

Follow the WAI-ARIA tabs pattern:

  • The tab container has role="tablist". Each tab has role="tab", aria-selected and aria-controls pointing to its panel.
  • Each panel has role="tabpanel" and aria-labelledby pointing to its tab.
  • ArrowRight and ArrowLeft move to the next and previous tab, wrapping around at the ends. Home and End jump to the first and last tab. Moving with the keyboard selects the tab and moves focus to it.
  • Only the selected tab is in the page's Tab order. Pressing Tab from it goes to the panel, not to the next tab.

Note

The preview updates as you type. There are no automated tests for this challenge yet: click the tabs, then use only the keyboard, then compare with the reference solution.

Follow-ups interviewers ask

  • Make it work as both controlled (value + onChange) and uncontrolled (defaultValue).
  • A compound-component API: <Tabs><Tabs.List><Tabs.Tab /></Tabs.List><Tabs.Panel /></Tabs>.
  • Manual activation: arrow keys move focus, and Enter or Space selects.
  • Keep inactive panels mounted (to preserve their state) versus unmounting them.

The approach

The only state is which tab is selected, stored by its id rather than its index. If the items list is reordered, the same tab stays selected.

Every panel is rendered, and the inactive ones get hidden. That keeps each tab's aria-controls pointing at an element that exists, and it is the simplest way to show one panel at a time.

Unique ids with useId

ARIA links tabs and panels by id. Hard-coding tab-html breaks as soon as two Tabs render the same item ids on one page. useId() returns an id that is unique to each component instance, and stable between the server and the client, so ${baseId}-tab-${id} is safe.

Keyboard: roving tabindex

A tab list is one stop in the page's Tab order, not one stop per tab. The selected tab gets tabIndex={0} and the others -1. Arrow keys then move between tabs:

Loading diagram...

One onKeyDown on the tablist handles every tab. The key-to-index lookup object keeps it short, and event.preventDefault() stops Home and End from scrolling the page.

Moving focus needs the DOM node, so the tabs register themselves in a Map held in a useRef, through a callback ref. A Map keyed by id stays correct when tabs are added or removed.

The panel is focusable

tabIndex={0} on the panel means Tab from the selected tab goes straight into its content. This matters when the panel has no focusable elements of its own: otherwise keyboard users would skip it.

What interviewers look for

  • Knowing the WAI-ARIA tabs pattern, especially the roving tabindex.
  • Storing the selected id, not a duplicate of the item.
  • useId for instance-safe ids.
  • A sensible answer to "controlled or uncontrolled", ideally supporting both.

Reference solution

src/Tabs.js

jsx
import { useId, useRef, useState } from 'react'

export default function Tabs({ items, defaultValue }) {
  const [activeId, setActiveId] = useState(defaultValue ?? items[0]?.id)
  const tabRefs = useRef(new Map())
  // Unique per Tabs instance, so two Tabs on one page never share element ids.
  const baseId = useId()
  const tabId = (id) => `${baseId}-tab-${id}`
  const panelId = (id) => `${baseId}-panel-${id}`

  function select(index) {
    const item = items[index]
    if (!item) return
    setActiveId(item.id)
    tabRefs.current.get(item.id)?.focus()
  }

  function onKeyDown(event) {
    const index = items.findIndex((item) => item.id === activeId)
    const last = items.length - 1
    const next = {
      ArrowRight: index === last ? 0 : index + 1,
      ArrowLeft: index === 0 ? last : index - 1,
      Home: 0,
      End: last,
    }[event.key]
    if (next === undefined) return
    event.preventDefault()
    select(next)
  }

  return (
    <div className="tabs">
      <div className="tab-list" role="tablist" onKeyDown={onKeyDown}>
        {items.map((item, index) => {
          const selected = item.id === activeId
          return (
            <button
              key={item.id}
              ref={(node) => {
                if (node) tabRefs.current.set(item.id, node)
                else tabRefs.current.delete(item.id)
              }}
              type="button"
              role="tab"
              id={tabId(item.id)}
              className="tab"
              aria-selected={selected}
              aria-controls={panelId(item.id)}
              // Roving tabindex: only the selected tab is in the Tab order.
              tabIndex={selected ? 0 : -1}
              onClick={() => select(index)}
            >
              {item.label}
            </button>
          )
        })}
      </div>
      {items.map((item) => (
        <div
          key={item.id}
          role="tabpanel"
          id={panelId(item.id)}
          className="tab-panel"
          aria-labelledby={tabId(item.id)}
          hidden={item.id !== activeId}
          tabIndex={0}
        >
          {item.content}
        </div>
      ))}
    </div>
  )
}