Created
January 7, 2019 20:11
-
-
Save 5t3ph/c25cb3a8f0d21f2475f346fbc0c5a8d9 to your computer and use it in GitHub Desktop.
Gatsby - Fetch permalink based on known slug
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
/* | |
* Usage: | |
* <Permalink label={component} slug={demo} /> | |
*/ | |
import * as React from 'react'; | |
import { StaticQuery, graphql } from 'gatsby'; | |
// Mimics function to test for internal v. external links from docs | |
// @link https://www.gatsbyjs.org/docs/gatsby-link/ | |
import Link from './Link'; | |
interface IPermalinkProps { | |
label: string; | |
slug: string; | |
data: { | |
allFile: { | |
edges: { | |
node: { | |
relativePath: string; | |
}; | |
}[]; | |
}; | |
}; | |
} | |
const Permalink: React.SFC<IPermalinkProps> = ({ label, slug, data }) => { | |
const pagePath = data.allFile.edges.filter((page) => { | |
const relativePath = page.node.relativePath.replace('.md', ''); | |
const re = RegExp(`${slug}$`, 'gi'); | |
return re.test(relativePath); | |
}); | |
if (pagePath[0]) { | |
const permalink = `/${pagePath[0].node.relativePath.replace('.md', '')}/`; | |
console.log(permalink); | |
return <Link href={permalink}>{label}</Link>; | |
} | |
return <>{label}</>; | |
}; | |
export default (props) => ( | |
<StaticQuery | |
query={graphql` | |
query { | |
allFile(filter: { internal: { mediaType: { eq: "text/markdown" } } }) { | |
edges { | |
node { | |
relativePath | |
} | |
} | |
} | |
} | |
`} | |
render={(data) => <Permalink data={data} {...props} />} | |
/> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment