Skip to content

Instantly share code, notes, and snippets.

@EliasAfara
Created June 25, 2023 01:21
Show Gist options
  • Save EliasAfara/d837ed056a528a619bea5b47d3066e48 to your computer and use it in GitHub Desktop.
Save EliasAfara/d837ed056a528a619bea5b47d3066e48 to your computer and use it in GitHub Desktop.
React scroll to top using react router dom
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