Scrolling to Elements with scrollIntoView
You'll learn how to programmatically scroll an element into view using refs and the native scrollIntoView() method.
What This Solves
Sometimes you need to scroll the page or a container so a specific element becomes visible—like jumping to an error message, highlighting a search result, or moving to the next section. With refs, you can control this imperatively.
The Core Pattern
Once you have a ref attached to a DOM element, you can call .scrollIntoView() on ref.current to make the browser scroll that element into the viewport:
function CommentSection() {
const errorRef = useRef(null);
function handleSubmit(e) {
e.preventDefault();
// Validation fails...
errorRef.current.scrollIntoView({ behavior: 'smooth' });
}
return (
<form onSubmit={handleSubmit}>
<input type="text" />
<button>Submit</button>
<div ref={errorRef} className="error">
Please fill out all fields
</div>
</form>
);
}
How It Works
- Create a ref with
useRef(null) - Attach it to the element you want to scroll to using the
refprop - Call
ref.current.scrollIntoView()in an event handler or effect - Optionally pass options like
{ behavior: 'smooth' }for animated scrolling
Common Options
behavior: 'smooth'— smooth animated scroll (default is instant)block: 'start'— align to top of viewportblock: 'center'— center the element
Key Takeaway: Use ref.current.scrollIntoView() to programmatically scroll any element into view, perfect for error messages, notifications, or navigating sections without managing scroll positions manually.