-
React / react-router-dom <Link /> 페이지 이동시 스크롤 상단위치 이슈 해결방법Web dev/React 2022. 4. 28. 23:32728x90반응형
리엑트로 포트폴리오 퍼블리싱중이다.
이전에는 몰랐는데 페이지가 하나둘 많아지면서 페이지이동할때 스크롤이 상단이 아닌 중간에 위치하는 이슈가 발견되었다.
리엑트는 SPA이기 때문에 <Link/>로 이동할 때 이런이슈가 발견된다.
해결법은 간단하다 app.js에서 BrowserRouter 밑에 설정해주면 된다.
브라우저라우터밑에 직접 쓸수도 있지만 깔끔하게 하려고 따로 빼주었다.
scrollToTop.jsx
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; };
useLocation 으로 pathname을 받아오고 useEffect로 pathname이 바뀔때 마다 이벤트를 발생시키면된다.
app.js
import React from "react"; import { HelmetProvider } from "react-helmet-async"; import {BrowserRouter,Routes,Route} from 'react-router-dom' import ScrollToTop from "./components/common/ScrollToTop"; import ItemDetailPage from "./pages/ItemDetailPage"; import ItemListPage from "./pages/ItemListPage"; import LoginPage from "./pages/LoginPage"; import MainPage from "./pages/MainPage"; import RegisterPage from "./pages/RegisterPage"; import SEO from "./SEO"; function App() { return ( <> <BrowserRouter> <HelmetProvider> <SEO/> <ScrollToTop/> <Routes> <Route element={<MainPage />} path="/"/> <Route element={<ItemListPage/>} path="/Itemlist/:category"/> <Route element={<ItemDetailPage />} path="/ItemDetail/:id"/> <Route element={<LoginPage />} path="/Login"/> <Route element={<RegisterPage />} path="/Register"/> </Routes> </HelmetProvider> </BrowserRouter> </> ); } export default App;
간단하게 이슈를 해결하였다 ㅎ-ㅎ
728x90반응형'Web dev > React' 카테고리의 다른 글
React / aside 기능구현시 page이동 scrollstop 이슈 (0) 2022.04.29 React / react-helmet 으로 동적으로 meta 태그 바꾸어주기 (0) 2022.04.29 React / useState, useEffect 로 background parallax 구현하기 (0) 2022.04.28 React / scroll stop 하면 나오는 배너 만들기 (0) 2022.04.16 React / heroku 에 json-server 배포하기 React deploy (0) 2022.04.16