Last active
February 25, 2021 18:30
-
-
Save drewkiimon/933a65c856ec3eac6d35779f6a7bf42d to your computer and use it in GitHub Desktop.
Dynamic MDX file import
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, { useEffect, useState } from "react"; | |
import { useRouter } from "next/router"; | |
import { MDXProvider } from "@mdx-js/react"; | |
const components = { | |
h1: (props: string) => <h1 style={{ color: "tomato" }} {...props} />, | |
}; | |
const Placeholder: React.FC = () => { | |
return <>Loading</>; | |
}; | |
interface Metadata { | |
title: string; | |
author: string; | |
} | |
interface MetadataState { | |
metadata: Metadata; | |
} | |
const BlogPost: React.FC = () => { | |
const router = useRouter(); | |
const { title } = router.query; | |
const [Component, setComponent] = useState<React.FC>(Placeholder); | |
const [metadata, setMetadata] = useState<MetadataState | null>(null); | |
useEffect(() => { | |
const getFile = async () => { | |
try { | |
if (title) { | |
let file = await import(`./../../_blog-posts/${title}.mdx`); | |
console.log(file); | |
setComponent(file.default); | |
setMetadata(file.metadata); | |
} | |
} catch (err) { | |
router.push("/blog"); | |
} | |
}; | |
getFile(); | |
}, [title]); | |
return <MDXProvider components={components}>{Component}</MDXProvider>; | |
}; | |
export default BlogPost; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment