Next.js Scroll behaviour on navigation with <Link >
Unanswered
Ocicat posted this in #help-forum
OcicatOP
Hi everyone,
I'm working on a Next.js 14 project with Tailwind and the app router. The landing page features a sticky navbar at the top, and users can scroll down through various sections in that page.
When you've scrolled down and click on the register button in the navbar to navigate there, the new page is displayed, but for a split second, it auto scrolls to the top.
After extensive searching for a solution, some recommended creating an _app.tsx file:
import { useEffect } from 'react';
import { useRouter } from 'next/router';
const MyApp = ({ Component, pageProps }) => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = () => {
window.scrollTo(0, 0);
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return <Component {...pageProps} />;
};
export default MyApp;
Another solution suggested involves reating a component with window.scrollTo(0, 0); and importing it as the first component on the page being navigated to. Unfortunately, neither of these solutions worked, and the auto-scrolling issue persisted, so I removed those files.
Is there a way to fix the issue once and for all? All I want is to navigate to a new page and have it display from the very top, regardless of how far down you have scrolled on the original page.
Any help would be greatly appreciated.
I'm working on a Next.js 14 project with Tailwind and the app router. The landing page features a sticky navbar at the top, and users can scroll down through various sections in that page.
When you've scrolled down and click on the register button in the navbar to navigate there, the new page is displayed, but for a split second, it auto scrolls to the top.
After extensive searching for a solution, some recommended creating an _app.tsx file:
import { useEffect } from 'react';
import { useRouter } from 'next/router';
const MyApp = ({ Component, pageProps }) => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = () => {
window.scrollTo(0, 0);
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return <Component {...pageProps} />;
};
export default MyApp;
Another solution suggested involves reating a component with window.scrollTo(0, 0); and importing it as the first component on the page being navigated to. Unfortunately, neither of these solutions worked, and the auto-scrolling issue persisted, so I removed those files.
Is there a way to fix the issue once and for all? All I want is to navigate to a new page and have it display from the very top, regardless of how far down you have scrolled on the original page.
Any help would be greatly appreciated.