0
0
NextJSframework~5 mins

Scroll behavior control in NextJS

Choose your learning style9 modes available
Introduction

Scroll behavior control lets you decide how the page moves when users click links or buttons. It helps make navigation smooth and clear.

When you want smooth scrolling to a section after clicking a link.
When you want to jump instantly to the top of the page after an action.
When you want to control scroll position after navigating between pages.
When you want to improve user experience by avoiding sudden jumps.
When you want to restore scroll position on back/forward browser actions.
Syntax
NextJS
window.scrollTo({ top: number, left: number, behavior: 'auto' | 'smooth' })
Use behavior: 'smooth' for smooth scrolling animation.
Coordinates top and left are in pixels from the page start.
Examples
Instantly scrolls to the top-left corner of the page.
NextJS
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
Smoothly scrolls down 500 pixels from the top.
NextJS
window.scrollTo({ top: 500, left: 0, behavior: 'smooth' })
Automatically scrolls to top smoothly after page navigation in Next.js.
NextJS
import { useEffect } from 'react';
import { useRouter } from 'next/router';

export default function ScrollToTop() {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = () => {
      window.scrollTo({ top: 0, left: 0, behavior: 'smooth' });
    };

    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return null;
}
Sample Program

This Next.js component shows a button that, when clicked, smoothly scrolls down to a section far below. The section is focusable for accessibility.

NextJS
import { useRef } from 'react';

export default function ScrollExample() {
  const sectionRef = useRef(null);

  function scrollToSection() {
    sectionRef.current?.scrollIntoView({ behavior: 'smooth' });
  }

  return (
    <main style={{ height: '150vh', padding: '1rem' }}>
      <button onClick={scrollToSection} aria-label="Scroll to section">
        Go to Section
      </button>
      <div style={{ marginTop: '100vh', padding: '1rem', backgroundColor: '#def' }} ref={sectionRef} tabIndex={-1} aria-label="Target section">
        <h2>Target Section</h2>
        <p>This is the section you scrolled to smoothly.</p>
      </div>
    </main>
  );
}
OutputSuccess
Important Notes

Use scrollIntoView on elements for easy smooth scrolling to parts of the page.

Remember to add aria-label and tabIndex for accessibility when scrolling to sections.

Test scroll behavior on different browsers as support may vary slightly.

Summary

Scroll behavior control improves how users move around your page.

Use window.scrollTo or element.scrollIntoView with behavior: 'smooth' for smooth scrolling.

In Next.js, you can listen to route changes to control scroll position after navigation.