Reputation: 53
I have an issue when I navigate to another page in my project. It starts from about halfway then scrolls to the top of the page. I would like it to automatically open up at the top of the page then be able to scroll down to view the rest of the page. This is my current code to scroll to top:
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
Upvotes: 1
Views: 362
Reputation: 203091
You can specify the scroll behavior by using the options version of window.scrollTo
.
An enum, the value of which can be one of the following:
- smooth: The scrolling animates smoothly.
- auto: The scrolling happens in a single jump.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo({
left: 0,
top: 0,
behavior: 'auto', // <-- The scrolling happens in a single jump
});
}, [pathname]);
return null;
}
Upvotes: 1