Skip to content

Refs to Many Elements

The Course
•
20 min study

useRef gives you one ref, and hooks can't be called in a loop. So how do you keep a ref to each card in a list, to scroll to whichever one is chosen?

Jump to a card React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useRef, useState } from "react"; import { manyCards } from "./manyCards.js"; export default function App() { const [highlighted, setHighlighted] = useState(null); const itemsRef = useRef(new Map()); function jumpTo(id) { const node = itemsRef.current.get(id); node.scrollIntoView({ block: "nearest" }); node.focus(); setHighlighted(id); } return ( <main> <h1>Study Board</h1> <div className="toolbar"> <select aria-label="Jump to" defaultValue="" onChange={(e) => jumpTo(Number(e.target.value))}> <option value="" disabled>Jump to a card</option> {manyCards.map((card) => ( <option key={card.id} value={card.id}>{card.title}</option> ))} </select> </div> <ul className="cards" style={{ maxHeight: "9rem", overflowY: "auto" }}> {manyCards.map((card) => ( <li key={card.id} tabIndex={-1} className={card.id === highlighted ? "card selected" : "card"} ref={(node) => { itemsRef.current.set(card.id, node); return () => { itemsRef.current.delete(card.id); }; }} > {card.title} </li> ))} </ul> <p className="muted">{manyCards.length} cards</p> </main> ); } export const manyCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, { id: 5, title: "Write reducer tests", column: "todo", minutes: 20 }, { id: 6, title: "Add undo", column: "doing", minutes: 25 }, { id: 7, title: "Split contexts", column: "todo", minutes: 15 }, { id: 8, title: "Use composition", column: "done", minutes: 15 }, { id: 9, title: "Focus a field", column: "todo", minutes: 10 }, { id: 10, title: "Measure renders", column: "todo", minutes: 20 }, { id: 11, title: "Try useTransition", column: "todo", minutes: 25 }, { id: 12, title: "Write a custom hook", column: "todo", minutes: 30 }, ]; 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; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Choose cards from Jump to a card. The list scrolls to the card, focuses it, and outlines it.

A ref callback

Instead of a ref object, you can pass ref a function:

JSX
<li
  ref={(node) => {
    itemsRef.current.set(card.id, node);
    return () => {
      itemsRef.current.delete(card.id);
    };
  }}
>

React calls it with the DOM element once the <li> exists. The function it returns is a cleanup, called when the element is removed or before React attaches a different callback ref. An inline ref callback has a new identity on each render, so React can detach and reattach it even when the DOM node stays. The add/delete operations must be safe to repeat. (Ref callback cleanups are new in React 19. Older code is called with null instead, and checks for it.)

A Map of elements

The one real useRef holds a Map from card id to element:

JavaScript
const itemsRef = useRef(new Map());

Each <li> adds itself when it appears and removes itself when it goes. To jump, jumpTo looks the element up by id and calls its DOM methods:

JavaScript
const node = itemsRef.current.get(id);
node.scrollIntoView({ block: "nearest" });
node.focus();

tabIndex={-1} on each <li> lets code focus it, without adding every card to the Tab order. Focusing the card means a screen reader announces it, and the keyboard continues from there.

Predict

The Map lives in a ref. Would anything change on screen if jumpTo only scrolled, without calling setHighlighted?

Check your prediction

The list would scroll, but no card would be outlined. Scrolling and focusing happen in the DOM, outside React. The outline comes from className, which depends on state, and only a state change re-renders.

Your turn

Exercise

Next and previous

Add Previous and Next buttons that jump to the card before or after the highlighted one. With nothing highlighted, Next goes to the first card.

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 { useRef, useState } from "react"; import { manyCards } from "./manyCards.js"; export default function App() { const [highlighted, setHighlighted] = useState(null); const itemsRef = useRef(new Map()); function jumpTo(id) { const node = itemsRef.current.get(id); node.scrollIntoView({ block: "nearest" }); node.focus(); setHighlighted(id); } return ( <main> <h1>Study Board</h1> <div className="toolbar"> <select aria-label="Jump to" defaultValue="" onChange={(e) => jumpTo(Number(e.target.value))}> <option value="" disabled>Jump to a card</option> {manyCards.map((card) => ( <option key={card.id} value={card.id}>{card.title}</option> ))} </select> </div> <ul className="cards" style={{ maxHeight: "9rem", overflowY: "auto" }}> {manyCards.map((card) => ( <li key={card.id} tabIndex={-1} className={card.id === highlighted ? "card selected" : "card"} ref={(node) => { itemsRef.current.set(card.id, node); return () => { itemsRef.current.delete(card.id); }; }} > {card.title} </li> ))} </ul> <p className="muted">{manyCards.length} cards</p> </main> ); } export const manyCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, { id: 5, title: "Write reducer tests", column: "todo", minutes: 20 }, { id: 6, title: "Add undo", column: "doing", minutes: 25 }, { id: 7, title: "Split contexts", column: "todo", minutes: 15 }, { id: 8, title: "Use composition", column: "done", minutes: 15 }, { id: 9, title: "Focus a field", column: "todo", minutes: 10 }, { id: 10, title: "Measure renders", column: "todo", minutes: 20 }, { id: 11, title: "Try useTransition", column: "todo", minutes: 25 }, { id: 12, title: "Write a custom hook", column: "todo", minutes: 30 }, ]; 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; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Find the highlighted card's index in manyCards with findIndex. It's -1 when nothing is highlighted, so index + 1 gives the first card.

Hint 2: a first step

Disable Previous at the first card and Next at the last, or clamp the index with Math.max and Math.min.

Show one solution
JavaScript
const index = manyCards.findIndex((card) => card.id === highlighted);

function step(offset) {
  const next = Math.min(Math.max(index + offset, 0), manyCards.length - 1);
  jumpTo(manyCards[next].id);
}
JSX
<button onClick={() => step(-1)} disabled={index <= 0}>Previous</button>
<button onClick={() => step(1)} disabled={index === manyCards.length - 1}>Next</button>

Was this article helpful?

Your response is saved on this device.