Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 08 / Topic 3 of 6

A ref as a DOM handle: scrolling to a section

The same DOM-handle idea scales to more than one node. examples/03_scroll_to_section_nav.jsx's MenuSectionNav keeps one ref per menu section, collected in a plain object inside a single useRef, so each nav button can scroll its own section into view:

// examples/03_scroll_to_section_nav.jsx
const sectionRefs = useRef({});

function scrollToSection(sectionId) {
  sectionRefs.current[sectionId]?.scrollIntoView({ behavior: "smooth" });
}
// ...
<section ref={(node) => { sectionRefs.current[sectionId] = node; }}>

A function passed as ref (instead of a ref object) is a ref callback - React calls it with the DOM node once it exists, so this component can stash several nodes inside one ref's .current, keyed by section id, without needing one useRef call per section. Clicking "Desserts" really calls scrollIntoView({ behavior: "smooth" }) on the desserts <section>'s own DOM node and never on the starters section's node (examples/03_scroll_to_section_nav.test.jsx) - jsdom has no real layout engine, so the test checks which node was asked to scroll, the same thing a browser would actually do with that call.

Done here? The practice set for Part 8 — including the solutions — is on the part page.

Search the guide