[Project] 페이지 이동 시, 화면을 맨 위로 자동 스크롤

    SMALL

    1. 문제

    재생목록을 클릭하면 페이지 이동을 하면서 재생목록의 상세페이지로 넘어가는 것을 구현하던 중!

     

    자동 스크롤 구현 전

     

    허걱.. 이동한 페이지가 맨 위로 자동 스크롤 되지 않는다는 것을 확인 !!

     

    나는 자동으로 맨 위로 스크롤 되고 있는 줄 알았다 ... ㅎㅎ

     

    이런 문제를 해결하는 것은 사용자가 좀 더 편한 웹사이트 사용을 할 수 있도록 돕는다.

     

    그렇다면 어떻게 해결할 수 있을까? 

     


    2. 해결법

    React 공식문서에도 이와 같은 내용이 기술되어 있다.

    https://v5.reactrouter.com/web/guides/scroll-restoration

     

    Home v6.14.1

    I'm on v5 The migration guide will help you migrate incrementally and keep shipping along the way. Or, do it all in one yolo commit! Either way, we've got you covered to start using the new features right away.

    reactrouter.com

     

    공식 문서에 따르면, Scroll Resortation이라고 불린다.

     

    공식 문서와 이해를 위한 추가 참고자료를 확인한 결과 해결법은 다음과 같다.

     

    간단한 프로세스는 (1) ScrollToTop 컴포넌트 만들기 (2) 만든 컴포넌트를 app.js, index.js에 넣어주기 이다.

     

    (1) ScrollToTop 컴포넌트 만들기

    // 페이지 이동 시, 스크롤 맨 위로
    import { useEffect } from "react";
    import { useLocation } from "react-router-dom";
    
    export default function ScrollToTop() {
        const {pathname} = useLocation();
    
        useEffect(() => {
            window.scrollTo(0,0); // 맨 위로 올림
        }, [pathname]);
    
        return null;
    }

     

    (2) 컴포넌트를 App.js / index.js 에 넣기

     

    ** 주의할 점: App.js와 index.js 중 <BrowserRouter>가 존재하는 파일에 컴포넌트를 import 해야 한다.

     

    참고자료만 보고 index.js에 넣었다가 오류가 발생했다 ㅎㅎ

     

    나의 경우 App.js에 경로들을 지정했기 때문에 ScrollToTop 컴포넌트를 App.js에 넣어줬다.

     

    // reacthook + function component 사용
    
    import React from 'react';
    import { BrowserRouter, Routes, Route, } from "react-router-dom";
    import Home from "./component/home";
    import AllMusic from "./component/allMusic";
    import MyMusic from "./component/myMusic";
    import PlayMusic from "./component/playMusic";
    import StoredPlaylist from "./component/storedPlaylist";
    import ScrollToTop from "./component/scrollToTop";
    
    
    function App() {
      return (
        <BrowserRouter>
        {/* 스크롤 맨 위로 올리기 위한 컴포넌트 */}
        <ScrollToTop/> 
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/MIMS" element={<Home />} />
            <Route path="/allMusic" element={<AllMusic/>}/>
            <Route path="/myMusic" element={<MyMusic/>}/>
            <Route path='/playMusic' element={<PlayMusic/>}/>
            <Route path='/storedPlaylist' element={<StoredPlaylist/>}/>
          </Routes>
        </BrowserRouter>
      );
    }
    
    export default App;

     

    이렇게 하니 !!!

     

    자동 스크롤 구현 후

     

    화면 최상단으로 자동 스크롤이 되었다!


    3. 참고 자료

    - https://v5.reactrouter.com/web/guides/scroll-restoration

    - https://dazzlynnnn.tistory.com/entry/React-Link%EB%A1%9C-%ED%8E%98%EC%9D%B4%EC%A7%80-%EC%9D%B4%EB%8F%99-%EC%8B%9C-%EB%A7%A8-%EC%9C%84%EB%A1%9C-%EC%8A%A4%ED%81%AC%EB%A1%A4

    - https://choijying21.tistory.com/84

    728x90

    댓글