-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: wrap all links in articles in next/link and add target _blank fo…
…r external links
- Loading branch information
Showing
4 changed files
with
87 additions
and
51 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import Link from 'next/link' | ||
import { cloneElement } from 'react' | ||
|
||
/** | ||
* isLinkOfSameHost checks if a link is of the same host as the host provided. | ||
* @param link relative or absolute link | ||
* @param host hostname with protocol prefix | ||
* @returns boolean | ||
*/ | ||
function isLinkOfSameHost(link: string, host: string) { | ||
try { | ||
const { origin: hostOrigin } = new URL(host) | ||
const { origin } = new URL(link, host) | ||
|
||
return origin === hostOrigin | ||
} catch (e) { | ||
return false | ||
} | ||
} | ||
|
||
const HrefLink = ({ | ||
href, | ||
passHref, | ||
legacyBehavior = true, | ||
children, | ||
...restProps | ||
}) => { | ||
if (!href) { | ||
return children | ||
} | ||
|
||
const isExternalLink = !isLinkOfSameHost( | ||
href, | ||
process.env.NEXT_PUBLIC_BASE_URL, | ||
) | ||
|
||
return ( | ||
<Link | ||
{...restProps} | ||
href={href} | ||
passHref={passHref} | ||
prefetch={false} | ||
legacyBehavior={legacyBehavior} | ||
> | ||
{legacyBehavior && isExternalLink | ||
? cloneElement(children, { target: '_blank', rel: 'noreferrer' }) | ||
: children} | ||
</Link> | ||
) | ||
} | ||
export default HrefLink |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters