External link is not working in Next.js when you want to use Link component

Mario Boss picture Mario Boss · Apr 6, 2020 · Viewed 25.7k times · Source

I was very surprised that a simple Link component is not working in Next.js when you want to use an external URL and HTML Button tag inside it.

Below you can see how I tried to solve the problem:

Approach number 1:

<Link href="https://stackoverflow.com/">
  <button>StackOverflow</button>
</Link>

Approach number 2 (link without protocol):

<Link href="//stackoverflow.com/">
  <button>StackOverflow</button>
</Link>

Approach number 3 (link without protocol and with Link attribute prefetch set to false or even true):

<Link href="//stackoverflow.com/" prefetch={false}>
  <button>StackOverflow</button>
</Link>

IMPORTANT NOTE

Of course, mentioned case it's working when the URL is internal, like that:

<Link href="/stackoverflow">
  <button>StackOverflow</button>
</Link>

or when I will change HTML button tag into HTML A tag, like that:

<Link href="//stackoverflow.com/">
  <a>StackOverflow</a>
</Link>

In my case, I want to use the HTML button tag or any other UI component inside the Next.js Link component.

Answer

Mario Boss picture Mario Boss · Apr 6, 2020

1. Solution for UI components inside Next.js Link component.

I have study Next.js documentation in more details and I found a very useful attribute to make an external link for any internal UI components (Semantic UI, Material UI, Reactstrap, etc.) inside Link component.

Let's take as an example a simple Semantic UI button component. To add an external link to the Next.js Link component we should use attribute passHref. This attribute is set to false by default. This attribute forces Link to send the href property to its child.

import { Button } from 'semantic-ui-react';
import Link from 'next/link';    

const Example = () => (
  <Link href="https://stackoverflow.com/" passHref={true}>
    <Button>StackOverflow</Button>
  </Link>
)

export default Example;

2. Solution for HTML elements (different that tag A)

Inside Next.js documentation you can find below sentences:

External URLs, and any links that don't require a route navigation using /pages, don't need to be handled with Link; use the anchor tag for such cases instead.

And I have to write that it is obvious, so in that case, if you need to use any other tag, for example, HTML button, you should use onClick event on it without Link component. The above code will look like this:

const clickHandle = () => {
  document.location.href = 'https://stackoverflow.com/';
}

const Example = () => (
  <button onClick={clickHandle}>StackOverflow</button>
)

export default Example;

I hope this kind of explanation and approach will help someone who will struggle with similar confusions.