I am facing an issue with React Router Dom v6 where my page goes blank after adding the scroll-to-top functionality. I have followed the documentation and tried different approaches, but I couldn’t find a solution. The page renders correctly without the scroll-to-top functionality.
I have created a GitHub repository for my project, which can be found at: https://github.com/AzureCloud9/arch-studio-multipage-website
Here is my App.js code:
import { createBrowserRouter, Route, createRoutesFromElements, RouterProvider } from "react-router-dom"
//Layout
import RootLayout from "./layout/RootLayout"
//pages
import Home from "./pages/home/Home"
import NotFound from "./pages/NotFound"
import Portfolio from './pages/portfolio/Portfolio'
import ScrollToTop from "./components/ScrollToTop"
const router = createBrowserRouter(
createRoutesFromElements(
<Route path='/' element={<RootLayout />}>
<ScrollToTop/>
<Route index element={<Home />} />
<Route path='/portfolio' element={<Portfolio/>}/>
<Route path='*' element={<NotFound />} />
</Route>
),
{
basename: '/arch-studio-multipage-website',
}
);
function App() {
return (
<RouterProvider router={router}/>
)
}
export default App
and here is my ScrollToTop.js code:
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
const ScrollToTop = () => {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
};
export default ScrollToTop;
I have checked for console errors and tried simplifying the code, but the issue persists. I would appreciate any assistance or guidance in resolving this problem.
2
Answers
The code snippet you provided doesn’t seem to include any sort of scroll-to-top functionality.
ScrollToTop
isn’t aRoute
component so it can’t be rendered as a child component of aRoute
. My suggestion would be to importScrollToTop
into theRootLayout
component and render it as part of the main app layout.Example:
src/layout/RootLayout.jsx
src/App.jsx
An alternative would be to convert
ScrollToTop
into a custom React hook.Example: