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.

Why do we need to have an < a > tag inside of a Link in NextJs?

When writing my first pages in NextJs I found it strange that all the <Link/> examples were pointing to a code like the one below:

<Link href="/to-some-page">
    <a>Go to another page</a>

Ok, it made sense to have a Link element so that we can get the super benefit of prefetching. But why the extra nesting for an <a> element? Why don't we just write:

<Link href="/to-some-page">Go to another page</Link>

Well, I found out that this is because of how the Link component works. Basically, it attaches an onClick event to its direct child component. The actual a element becomes:

<a onclick={goToPageFunction}>Go to another page</a>

Therefore, it needs a child component to attach the onClick event to it.

The nice stuff is that we can set also other types of elements as children of a Link. Do you want a button or a span to act as a link? No problem. Just do:

<Link href="/to-some-page">
    <button>This button redirects to /to-some-page url</button>

But what about SEO? Indeed, how can we get the SEO benefits given that the actual URL from the href of the Link it's used in the onClick function? Google uses the hrefs values as trust votes for its search mechanism.

Well, in case we want to communicate to the search bots our vote for a specific page we can use the passHref property. You will also want to use passHref if you used styled a components in NextJs. See more about this in the official docs.

Btw, in case you are interested in other out-of-the-box functionalities of the Link component in NextJs I've written another article about it. Check it out here.

Home Screencasts Best of Newsletter Search X