Command Palette

Search for a command to run...

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

Locking page scroll behind a modal

The hook saves the old inline styles and restores them in its cleanup, so nested modals unlock in the right order. Open the modal and try to scroll the page: it doesn't move, and scrolling past the end of the terms doesn't chain to the page.

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?

Locking page scroll behind a modal

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Closed: page overflow is ''
Open: page overflow is 'hidden'
Closed again: page overflow is ''