Link Component:
Link is one of the built-in components in the next.js framework. It performs client-side navigation between pages in a next.js application. It's generally preferred over using the native anchor <a>
element for routing in next.js app.
When we use the next.js Link Component, it will render an HTML <a>
tag under the hood, with an href
attribute pointing to the specified page without a full page refresh.
To use the next.js Link component, import it at the top of the page from next/link
module, and pass an href
prop to the component:
The Link component props #
Various props can be registered on a next.js Link component to customize the navigation behaviour.
Required props :
href:
The path or URL to navigate to.
The destination URL that's provided as a value to the href
prop, is where the user will be sent after clicking on the link.
//Relative URL
<Link href="/dashboard">Dashboard</Link>
//Absolute URL
<Link href="https://nextjs.org/docs"> Read the Docs </Link>
href
can also accept an object, for example:
// Navigate to /about?name=test
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About
</Link>
Some optional props :
prefetch:
Theprefetch
prop allows the preloading of pages in the background and is enabled by default in the next.js Link component. It only works in production, and if you wish to disable preloading, you can configure it like so:
<Link href='/products' prefetch={false}> Click me! </Link>
replace:
Default tofalse
. Whentrue
,next/link
will replace the current history state instead of adding a new URL into the browser's history stack.
When you navigate to a new URL, usually that URL is added to the history stack. Clicking on the back button in the navigation bar in the browser will take you back to the previous page in the stack.
The replace
prop changes this navigation behaviour by replacing the current history state instead.
import Link from 'next/link'
export default function Page() {
return (
<Link href="/dashboard" replace>
Dashboard
</Link>
)
}
Next.js Link Style
In next.js, we can style links using CSS. There are several ways to do this, but one common approach is to use the className attribute to apply a CSS class to the link, and then define the styles for that class in our CSS file.
If we’re using a CSS framework like Bootstrap or Tailwind, we can also use their utility classes to style links.
Conclusion #
The Link component is a powerful tool for creating dynamic and interactive application linking mechanism. Due to its built-in features including preloading page content and faster navigation, it helps improve application performance and SEO ranking and gives a significant user experience.