Created
June 25, 2023 01:21
-
-
Save EliasAfara/d837ed056a528a619bea5b47d3066e48 to your computer and use it in GitHub Desktop.
React scroll to top using react router dom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect } from "react"; | |
import { useLocation } from "react-router-dom"; | |
const ScrollToTop = () => { | |
const location = useLocation(); | |
console.log(location); | |
useEffect(() => { | |
try { | |
// trying to use new API - https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo | |
window.scroll({ | |
top: 0, | |
left: 0, | |
behavior: "smooth", | |
}); | |
} catch (error) { | |
// just a fallback for older browsers | |
window.scrollTo(0, 0); | |
} | |
}, [location.pathname]); | |
// renders nothing, since nothing is needed | |
return null; | |
}; | |
export default ScrollToTop; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment