Common DOM Operations: Scroll
What you'll learn: How to programmatically control scroll position using refs and native scroll methods.
The Core Idea
Just like you used refs to call .focus() on an input, you can use them to control where the user's viewport is positioned on the page. This is useful for "scroll to top" buttons, navigating to sections, or highlighting newly added items.
The main method you'll use is scrollIntoView(), which scrolls the page (or a scrollable container) until the referenced element is visible.
Basic Scroll Operations
Once you have a ref attached to a DOM element, you can call:
const sectionRef = useRef(null);
// Inside an event handler or effect:
sectionRef.current.scrollIntoView();
This scrolls the element into the visible area. You can control how it scrolls:
sectionRef.current.scrollIntoView({
behavior: 'smooth', // animated scroll
block: 'start' // align to top of viewport
});
Other Scroll Methods
The DOM also provides:
element.scrollTop = value— set vertical scroll positionelement.scrollLeft = value— set horizontal scroll positionwindow.scrollTo(x, y)— scroll the window to coordinates
All of these can be triggered from event handlers (like button clicks) or effects (like "scroll to bottom when new message arrives").
Analogy
Think of refs as remote controls for DOM elements. With .focus(), you're pressing the "select this input" button. With .scrollIntoView(), you're pressing "bring this element onto the screen."
Key Takeaway: Use ref.current.scrollIntoView() to programmatically scroll elements into view, typically from event handlers or effects after the DOM is ready.