šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on 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>
</Link>

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>
</Link>

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.

šŸ“– 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.


Leave a Reply

Your email address will not be published. Required fields are marked *