Link is maybe the most used building component from NextJs. This article aims to explore some of its most known (and less unknown) features.
So, let's start by seeing it in action. First, we will need to import it from next/link
and use its href
attribute to allow the user to navigate to different pages.
import Link from 'next/link'
export default ()=> {
return (<nav>
<Link href="/home"><a>Index</a></Link>
<Link href="/contact"><a>Contact</a></Link>
</nav>)
}
NextJs using objects as hrefs for a Link
One lesser-known fact about the href
is that you can also send it a javascript object as a parameter. This provides a nicer separation between the actual path and query parameters:
const obj1 = {
pathname: '/blog/[slug]',
query: { slug: 'my-post' }
}
const obj2 = {
pathname: '/about',
query: { name: 'test' }
}
// will link to /blog/my-post
<Link href={obj1}>Link1</Link>
// will link to /about?name=test
<Link href={obj2}>Link2</Link>
NextJs remove the prefeching for a Link
One huge performance advantage of using the Link component is its prefeching capability for the linked local pages. If you want to reduce the data usage and disable prefetching you can say:
<Link href={url} prefetch={false}>
<a>Open link</a>
</Link>
However keep in mind that prefetching will still take place on the hover event for the Link
elements, even if prefetch is set to false.
Links in NextJs using replace and scroll
Two other properties that allow extra customization are the replace
and scroll
attributes. The first one will replace the current url in the browser history (the back button will not work). While the second one will prevent scrolling to the target page top, or hash id if provided:
<Link href={url} replace scroll={false}>
<a>Goto link</a>
</Link>
NextJs open a Link in a new tab
And a final tip. If you want to open a <Link />
in a new tab you can do:
<Link href={url}>
<a target="_blank" rel="noopener">Open this in a new tab</a>
</Link>
Be sure to take a look at the official documentation and if you are wondering why we need to place an <a>
inside of an <Link>
I've written another article about this here.
And speaking of opening links in new tabs don't forget to include the rel="noopener"
in order to avoid any security vulnerabilities.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.