Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 24.3 — Scroll Behaviour
React · Example 2 of 4

scrollIntoView, scroll-margin and a scroll spy

Clicking API scrolls smoothly, and the spy marks each section as it passes the band under the header. scroll-margin-top: 40px makes the heading stop below the sticky header instead of under it. Click the links yourself.

Scrolling is part of the UX you build: new pages start at the top, Back returns to where the user was, links and buttons scroll smoothly to the right place below sticky headers, a table of contents highlights the section in view, chats stay pinned to the newest message only when the reader is there, and modals stop the page behind them from scrolling.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a useScrollToTopOnPush(ref) hook for a router app that scrolls a container to the top on PUSH navigations only.

02

Add a "Back to top" button to a long page that appears after scrolling 400px and respects reduced motion.

Explain it without notes

01

Why does an SPA need its own scroll restoration, and how would you implement it?

02

How do you scroll to a section without it ending up under a sticky header?

03

How would you implement a scroll spy for a table of contents?

04

Describe the scroll rules a chat window needs.

05

How do you stop the page from scrolling behind a modal, and what are the gotchas?

scrollIntoView, scroll-margin and a scroll spy

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Active section: Intro
Active section: Install
Active section: Usage
Active section: API
API heading clear of the 40px sticky header: true