Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Exploring the Link component in NextJs: objects as hrefs, disabling prefetching and page scroll, opening in new tab

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>)
}

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>

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.

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>

And a final tip. If you want to open a <Link /> in a new tab you can do:

<Link href={url}>
  <a target="_blank">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.

Home Screencasts Best of Newsletter Search X