Skip to content

Arrow Keys and Roving Focus

The Course
•
20 min study

The Day 1 tabs work with a mouse. With a keyboard, each tab is a separate Tab stop, which isn't what users of tabs expect. Tabs, toolbars, menus and radio groups are one stop: Tab moves into the group, the arrow keys move within it, and Tab again leaves it.

Tabs with arrow keys React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Tab, TabList, TabPanel, Tabs } from "./Tabs.jsx"; export default function App() { return ( <main> <h1>Study Hub</h1> <button>Before the tabs</button> <Tabs defaultValue="today"> <TabList label="Study Hub sections"> <Tab value="today">Today</Tab> <Tab value="topics">Topics</Tab> <Tab value="stats">Stats</Tab> </TabList> <TabPanel value="today"><p>Three cards to study.</p></TabPanel> <TabPanel value="topics"><p>Reducers, context, refs and Suspense.</p></TabPanel> <TabPanel value="stats"><p>A 4-day streak.</p></TabPanel> </Tabs> <button>After the tabs</button> </main> ); } import { createContext, useContext, useId, useRef, useState } from "react"; const TabsContext = createContext(null); function useTabs(part) { const tabs = useContext(TabsContext); if (tabs === null) throw new Error(`<${part}> must be used inside <Tabs>.`); return tabs; } export function Tabs({ defaultValue, children }) { const [selected, setSelected] = useState(defaultValue); const baseId = useId(); return <TabsContext value={{ selected, setSelected, baseId }}>{children}</TabsContext>; } export function TabList({ label, children }) { useTabs("TabList"); const listRef = useRef(null); function handleKeyDown(event) { const tabs = [...listRef.current.querySelectorAll('[role="tab"]')]; const index = tabs.indexOf(document.activeElement); const next = { ArrowRight: (index + 1) % tabs.length, ArrowLeft: (index - 1 + tabs.length) % tabs.length, Home: 0, End: tabs.length - 1, }[event.key]; if (next === undefined) return; event.preventDefault(); tabs[next].focus(); tabs[next].click(); } return ( <div role="tablist" aria-label={label} ref={listRef} onKeyDown={handleKeyDown}> {children} </div> ); } export function Tab({ value, children }) { const { selected, setSelected, baseId } = useTabs("Tab"); const isSelected = selected === value; return ( <button role="tab" id={`${baseId}-tab-${value}`} aria-selected={isSelected} aria-controls={`${baseId}-panel-${value}`} tabIndex={isSelected ? 0 : -1} onClick={() => setSelected(value)} > {children} </button> ); } export function TabPanel({ value, children }) { const { selected, baseId } = useTabs("TabPanel"); if (selected !== value) return null; return ( <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`} tabIndex={0}> {children} </div> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Click Before the tabs, then press Tab. Use the arrow keys, Home and End, then press Tab again.

Roving tabindex

Only the selected tab is in the Tab order. The others are skipped:

JavaScript
tabIndex={isSelected ? 0 : -1}

tabIndex={-1} means "focusable by code, but not by Tab". As the selection moves, the 0 moves with it, which is why it's called a roving tabindex.

Arrow keys

TabList handles the keys for the whole group:

JavaScript
const next = {
  ArrowRight: (index + 1) % tabs.length,
  ArrowLeft: (index - 1 + tabs.length) % tabs.length,
  Home: 0,
  End: tabs.length - 1,
}[event.key];

It focuses the next tab and clicks it, so focusing a tab also selects it. This is automatic activation, suitable when panels appear without a noticeable wait. A tab that starts a slow request can instead use manual activation: arrows move focus, and Enter or Space selects. Don't make keyboard users wait through a request for every tab they pass. Right from the last tab wraps to the first. preventDefault stops the arrow keys scrolling the page:

JavaScript
function handleKeyDown(event) {
  const tabs = [...listRef.current.querySelectorAll('[role="tab"]')];
  const index = tabs.indexOf(document.activeElement);
  const next = {
    ArrowRight: (index + 1) % tabs.length,
    ArrowLeft: (index - 1 + tabs.length) % tabs.length,
    Home: 0,
    End: tabs.length - 1,
  }[event.key];
  if (next === undefined) return;
  event.preventDefault();
  tabs[next].focus();
  tabs[next].click();
}

The tab panel has tabIndex={0}, so the next Tab moves into the panel's content, as the pattern recommends.

Predict

From Today, press Tab once. Where does focus go: Topics, or the panel?

Check your prediction

The panel. Topics has tabIndex={-1}, so Tab skips it. The tabs are one stop; the arrow keys move between them.

Exercise

A toolbar

Above the tabs, add a toolbar with three buttons, Bold, Italic and Code, as one Tab stop with Left and Right arrows. Unlike tabs, moving focus doesn't press a button. The last one focused keeps the 0.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Tab, TabList, TabPanel, Tabs } from "./Tabs.jsx"; export default function App() { return ( <main> <h1>Study Hub</h1> <button>Before the tabs</button> <Tabs defaultValue="today"> <TabList label="Study Hub sections"> <Tab value="today">Today</Tab> <Tab value="topics">Topics</Tab> <Tab value="stats">Stats</Tab> </TabList> <TabPanel value="today"><p>Three cards to study.</p></TabPanel> <TabPanel value="topics"><p>Reducers, context, refs and Suspense.</p></TabPanel> <TabPanel value="stats"><p>A 4-day streak.</p></TabPanel> </Tabs> <button>After the tabs</button> </main> ); } import { createContext, useContext, useId, useRef, useState } from "react"; const TabsContext = createContext(null); function useTabs(part) { const tabs = useContext(TabsContext); if (tabs === null) throw new Error(`<${part}> must be used inside <Tabs>.`); return tabs; } export function Tabs({ defaultValue, children }) { const [selected, setSelected] = useState(defaultValue); const baseId = useId(); return <TabsContext value={{ selected, setSelected, baseId }}>{children}</TabsContext>; } export function TabList({ label, children }) { useTabs("TabList"); const listRef = useRef(null); function handleKeyDown(event) { const tabs = [...listRef.current.querySelectorAll('[role="tab"]')]; const index = tabs.indexOf(document.activeElement); const next = { ArrowRight: (index + 1) % tabs.length, ArrowLeft: (index - 1 + tabs.length) % tabs.length, Home: 0, End: tabs.length - 1, }[event.key]; if (next === undefined) return; event.preventDefault(); tabs[next].focus(); tabs[next].click(); } return ( <div role="tablist" aria-label={label} ref={listRef} onKeyDown={handleKeyDown}> {children} </div> ); } export function Tab({ value, children }) { const { selected, setSelected, baseId } = useTabs("Tab"); const isSelected = selected === value; return ( <button role="tab" id={`${baseId}-tab-${value}`} aria-selected={isSelected} aria-controls={`${baseId}-panel-${value}`} tabIndex={isSelected ? 0 : -1} onClick={() => setSelected(value)} > {children} </button> ); } export function TabPanel({ value, children }) { const { selected, baseId } = useTabs("TabPanel"); if (selected !== value) return null; return ( <div role="tabpanel" id={`${baseId}-panel-${value}`} aria-labelledby={`${baseId}-tab-${value}`} tabIndex={0}> {children} </div> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Remember the index of the button that has the Tab stop: const [current, setCurrent] = useState(0);.

Hint 2: a first step

<div role="toolbar" aria-label="Formatting" onKeyDown={...}>, and each button tabIndex={i === current ? 0 : -1}. Focus the new button with a ref or querySelectorAll("button").

Show one solution
JSX
function Toolbar() {
  const [current, setCurrent] = useState(0);
  const ref = useRef(null);
  const items = ["Bold", "Italic", "Code"];

  function handleKeyDown(event) {
    const delta = { ArrowRight: 1, ArrowLeft: -1 }[event.key];
    if (!delta) return;
    event.preventDefault();
    const next = (current + delta + items.length) % items.length;
    setCurrent(next);
    ref.current.querySelectorAll("button")[next].focus();
  }

  return (
    <div role="toolbar" aria-label="Formatting" ref={ref} onKeyDown={handleKeyDown}>
      {items.map((item, i) => (
        <button key={item} tabIndex={i === current ? 0 : -1} onFocus={() => setCurrent(i)}>
          {item}
        </button>
      ))}
    </div>
  );
}

Import useRef and useState in App.jsx. onFocus keeps the stop in place when a button is clicked with the mouse.

Was this article helpful?

Your response is saved on this device.