How to scroll back to top when switching screens in React JS and Lenis smooth scrolling
P粉662614213
2023-08-18 09:58:58
<p>I am using lenis to achieve smooth scrolling and I have a ScrollToTop.js file which I use in my App.js. It works fine when the page is not scrolling, but when I click a button that takes me to another page and the "smooth scrolling" is happening, scrollToTop doesn't work, does anyone know how to fix this? </p>
<p>ScrollToTop.js</p>
<pre class="brush:php;toolbar:false;">import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { gsap } from "gsap";
import { colors } from "./constants";
export default function ScrollToTop() {
const { pathname } = useLocation();
const body = document.querySelector("body");
useEffect(() => {
window.scrollTo(0, 0);
// gsap.to(body, { duration: 0, backgroundColor: colors.white });
}, [pathname]);
return null;
}</pre>
<p>I've tried using useLayoutEffect in every page but it doesn't work</p>
As others have pointed out, you are wrapping your Routes component with a ScrollToTop component, but I recommend converting it to a React hook rather than editing it to render its implicit children property, especially considering that it actually Doesn't render anything, you want it to run as a side effect of navigation.