Today I Learn/React

[Next.js] 뒤로가기 시 스크롤 위치 유지하기(scrollRestoration)

단추언니 2023. 3. 31. 11:37
반응형

next.js에서 스크롤 위치 복원 구현하는 방법

페이지 이동 후 뒤로가기 버튼을 선택하면 페이지 상단으로 스크롤이 이동되지 않고 스크롤이 유지되기를 원했다.

 

1. next.js는 scrollRestoration을 기본적으로 지원한다. next.config.js 파일에서 scrollRestoration을 true로 설정해주기만 하면 된다. 하지만 이 방법은 실험적인 방법이라고 하며 내 프로젝트에서는 동작하지 않았다.

 

const nextConfig = {

  experimental: {
    scrollRestoration: true,
  },
};

module.exports = nextConfig;

 

2. 브라우저의 세션스토리지를 사용하는 방법

import { useEffect } from 'react';
import { useRouter } from 'next/router';

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

  useEffect(() => {
    if ('scrollRestoration' in history && history.scrollRestoration !== 'manual') {
      history.scrollRestoration = 'manual';
    }
  }, []);

  useEffect(() => {
    const handleRouteChange = () => {
      sessionStorage.setItem('scrollPosition', window.scrollY.toString());
    };
    router.events.on('routeChangeStart', handleRouteChange);
    return () => {
      router.events.off('routeChangeStart', handleRouteChange);
    };
  }, [router.events]);

  useEffect(() => {
    if ('scrollPosition' in sessionStorage) {
      window.scrollTo(0, Number(sessionStorage.getItem('scrollPosition')));
      sessionStorage.removeItem('scrollPosition');
    }
  }, []);

  return (
    <>
       ...
    </>
  );
}

 

코드 설명

useEffect(() => {
    if ('scrollRestoration' in history && history.scrollRestoration !== 'manual') {
      history.scrollRestoration = 'manual';
    }
  }, []);

scrollRestoration 은 히스토리 네비게이션의 스크롤 복원 기능을 명시적으로 지정할 수 있는 속성이다. Next.js에서는 기본적으로 auto로 설정되어 있기 때문에 수동적으로 설정할 것이라는 명시를 해주어야 한다.

useEffect(() => {
    const handleRouteChange = () => {
      sessionStorage.setItem('scrollPosition', window.scrollY.toString());
    };
    router.events.on('routeChangeStart', handleRouteChange);
    return () => {
      router.events.off('routeChangeStart', handleRouteChange);
    };
  }, [router.events]);

두 번째 hooks에서는 경로가 변경되거나 사용자가 다른 페이지로 이동할 때마다 사용자의 스크롤 위치를 브라우저의 세션 저장소에 변수로 저장해준다. 이렇게 설정하면 사용자가 뒤로가기 버튼을 선택했을 때 스크롤 위치 유지가 가능하다.

useEffect(() => {
    if ('scrollPosition' in sessionStorage) {
      window.scrollTo(0, Number(sessionStorage.getItem('scrollPosition')));
      sessionStorage.removeItem('scrollPosition');
    }
  }, []);

마지막으로 scrollPosition변수의 값을 사용하여 사용자 스크롤 위치를 이전 위치로 설정하는 역할을 한다. 스크롤 위치가 설정되면 세션 저장소에서 변수를 제거한다. 이는 사용자가 이전 페이지로 돌아가면 더 이상 변수를 저장할 필요가 없기 때문이다.

반응형