Last active
April 19, 2020 10:46
-
-
Save Js-Brecht/f9afa32bed37fa5946d7d6780804901d to your computer and use it in GitHub Desktop.
Internal/External Gatsby Link
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 React from 'react'; | |
import { PropTypes } from 'prop-types'; | |
import { useStaticQuery, graphql, withPrefix } from 'gatsby'; | |
import GatsbyLink from 'gatsby-link'; | |
const DOMAIN_PATTERN = /^(?:https?:)?[/]{2,}([^/]+)/; | |
const HASH_PATTERN = /^#.*/; | |
const INTERNAL_PATTERN = /^\/(?!\/)/; | |
const FILE_PATTERN = /.*[/](.+\.[^/]+?)([/].*?)?([#?].*)?$/; | |
const getDomain = (href) => { | |
const matches = DOMAIN_PATTERN.exec(href); | |
return matches ? matches[1] : "" | |
} | |
const isHashHref = (href) => HASH_PATTERN.test(href); | |
const isFileHref = (href) => { | |
const matches = FILE_PATTERN.exec(href); | |
if (!matches) return false; | |
if (matches[1]) { | |
// Files won't have additional path segments following them | |
if (matches[2] && /[^/]/.test(matches[2])) return false; | |
return true; | |
} | |
return false; | |
} | |
const isInternalHref = (href, siteUrl) => { | |
if (INTERNAL_PATTERN.test(href)) return true; | |
const targetDomain = getDomain(href); | |
const localDomain = targetDomain && siteUrl && getDomain(siteUrl); | |
return localDomain && targetDomain === localDomain; | |
} | |
export const Link = (props) => { | |
const { site: { siteMetadata: { siteUrl } } } = useStaticQuery(graphql` | |
query { | |
site { | |
siteMetadata { | |
siteUrl | |
} | |
} | |
} | |
`) | |
const { to } = props; | |
const isHash = isHashHref(to); | |
const isFile = !isHash && isFileHref(to); | |
const isInternal = !isHash && isInternalHref(to, siteUrl); | |
if (isHash || isFile || !isInternal) { | |
return <a {...props} href={isInternal && isFile ? withPrefix(to) : to} />; | |
} else { | |
return <GatsbyLink {...props} /> | |
} | |
} | |
Link.propTypes = { | |
to: PropTypes.string.isRequired, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment