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

Smooth Scrolling with Behavior Options

Pass { behavior: 'smooth', block: 'nearest' } to scrollIntoView for animated scroll transitions.

Smooth Scrolling with Behavior Options

What you'll learn: How to make your scrollIntoView() calls visually smooth and control scroll alignment with behavior options.

The Problem with Instant Scrolling

In the previous lesson, you learned to use ref.current.scrollIntoView() to jump directly to an element. But instant jumps can be jarring—users might not realize what just happened or where they ended up on the page.

Adding Smooth Animation

The scrollIntoView() method accepts an options object that controls how the scroll happens. The most important option is behavior:

function ScrollExample() {
  const targetRef = useRef(null);

  const handleScroll = () => {
    targetRef.current.scrollIntoView({ 
      behavior: 'smooth' 
    });
  };

  return (
    <>
      <button onClick={handleScroll}>Scroll Down</button>
      <div style={{ height: '150vh' }} />
      <div ref={targetRef}>Target Section</div>
    </>
  );
}

Instead of an instant jump, the browser now animates the scroll smoothly.

Controlling Alignment with block

The block option controls vertical alignment:

  • 'start' - Top of element aligns with viewport top
  • 'center' - Element centered in viewport
  • 'end' - Bottom of element aligns with viewport bottom
  • 'nearest' - Scrolls the minimum distance needed
targetRef.current.scrollIntoView({ 
  behavior: 'smooth',
  block: 'nearest'  // Only scrolls if element isn't visible
});

Think of it like this: 'nearest' is the polite option—it only scrolls if absolutely necessary, avoiding unnecessary motion.

Combining Options

targetRef.current.scrollIntoView({ 
  behavior: 'smooth',
  block: 'center'  // Smoothly centers the element
});

Key Takeaway: Pass { behavior: 'smooth' } to scrollIntoView() for animated transitions, and use block: 'nearest' to minimize scroll distance, creating a better user experience than instant jumps.