The issue you're facing is related to how <Link>
works in Next.js.
By default, when using <Link>
, it will scroll to the top of the page before navigating. This behavior is explained in the Link Documentation, and it's intended to ensure that users start from a consistent position when moving between pages. However, in your case, where you want to stay on the same page, this behavior needs to be overridden.
You can prevent this default behavior by adding scroll={false}
to your <Link>
component. This should resolve the scrolling issue, but there may be additional considerations depending on how you've implemented smooth scrolling and other aspects of Next.js. (Nevertheless, addressing this initial problem should help)
To implement this change, your code snippet should look like this:
<Link href="#link" scroll={false}>
In addition, consider utilizing the _document.js
file provided by Next.js to manipulate properties of the body
and html
elements.
Based on your example, here's a suggested approach:
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html className="scroll-smooth">
<Head />
<body className="bg-[#ecf0f3] text-[#1f2937] tracking-wide ">
<Main />
<NextScript />
</body>
</Html>
)
}
This approach allows for a cleaner CSS setup and ensures that the desired behavior is consistently applied to every page rendered in Next.js (as _document.js serves as the "template").
It's also recommended to remove the unnecessary "/" before the #id in your href attribute.
Additional Resources:
_document.js documentation
Tailwind Smooth Scroll