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;
UPDATE:
Of course, I agree with devs who are writing that for external links we should not use the Link component. The best solution here is to use just pure HTML a
tags or JS redirect solution on click event as it has been shown in point 2 (or any similar way). Worth to mention, that you can build your own component and based on the passed href
attribute you can switch between Link
component and HTML a
tag, like that:
// custom simple smart Link component
import Link from 'next/link';
const SmartLink = (link, url) => {
const regEx = /^http/;
return regEx.test(url) ? <Link href={url}>{link}</Link> : <a href={url}>{link}</a>;
}
export default SmartLink;
// ways to call the component
import SmartLink from 'path/to/SmartLink'; // set correct path
// somewhere inside the render method
// the below will use HTML A tag
<SmartLink href="https://stackoverflow.com" link="external StackOverflow website" />
// the below will use Next.js Link component
<SmartLink href="/stackoverflow" link="internal StackOverflow page" />
const URL = ({ link }) => { const { type, url } = link return ( <ListItem style={{ width: "inherit", display: "inline-block" }}> <a href={url}> <ListItemIcon> { { Github: <GitHub />, BitBucket: <InsertLink />, GitLab: <InsertLink />, StackOverflow: <InsertLink />, LinkedIn: <LinkedIn />, }[type] } </ListItemIcon> </a> </ListItem> ) }
This one @Mario Boss – Halle