search

Home  >  Q&A  >  body text

How to scroll back to top when switching screens in React JS and Lenis smooth scrolling

<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>
P粉662614213P粉662614213497 days ago691

reply all(1)I'll reply

  • P粉198814372

    P粉1988143722023-08-19 09:18:53

    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.

    reply
    0
  • Cancelreply