Course contentsShow
← React
Lesson 735 of 2,39619. useRefFree lesson

Scrolling to Elements with scrollIntoView

Use ref.current.scrollIntoView() to programmatically scroll an element into the viewport.

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

  1. Create a ref with useRef(null)
  2. Attach it to the element you want to scroll to using the ref prop
  3. Call ref.current.scrollIntoView() in an event handler or effect
  4. 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 viewport
  • block: '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.