Skip to content

Instantly share code, notes, and snippets.

@drewkiimon
Last active February 25, 2021 18:30
Show Gist options
  • Save drewkiimon/933a65c856ec3eac6d35779f6a7bf42d to your computer and use it in GitHub Desktop.
Save drewkiimon/933a65c856ec3eac6d35779f6a7bf42d to your computer and use it in GitHub Desktop.
Dynamic MDX file import
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