Created
June 22, 2022 13:12
-
-
Save alexcarpenter/59599fa097537ed9e978818b256ec391 to your computer and use it in GitHub Desktop.
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
import PropTypes from 'prop-types' | |
import Link from 'next/link' | |
β | |
// Checks against absolute URLs that share π so | |
// we can still pass it along to our internal link component | |
const domainRegex = /http[s]*:\/\/[www.]*YOURDOMAIN\.com[/]?/ | |
β | |
const TextLink = ({ href, ...rest }) => { | |
const sameDomain = domainRegex.test(href) | |
β | |
// If our link matches the `domainRegex` above, | |
// update to become relative | |
if (sameDomain) { | |
href = href.replace(domainRegex, '/') | |
} | |
β | |
// If our link is relative, we can assume it's | |
// an internal link and use `next/link` | |
if (href.startsWith('/')) { | |
return ( | |
<Link href={href}> | |
<a {...rest} /> | |
</Link> | |
) | |
} | |
β | |
// Treat urls that aren't http protocols as | |
// "normal" links | |
if (!href.startsWith('http')) { | |
return <a href={href} {...rest} /> | |
} | |
β | |
// Otherwise, this is an external link that | |
// we can add on good security defaults for | |
return ( | |
<a | |
href={href} | |
target="_blank" | |
rel="noopener noreferrer nofollow" | |
{...rest} | |
/> | |
) | |
} | |
β | |
TextLink.propTypes = { | |
href: PropTypes.string.isRequired, | |
} | |
β | |
export default TextLink |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment