How to render MDX string as a react component? #13901
-
This is my This is my I have a hierarchy like this for my blog. I'm dynamically creating blog links using export async function getStaticPaths() {
const fs = require("fs");
const path = require("path");
const filesString = fs.readdirSync(path.join("content", "posts/")).toString();
const linksArray = filesString.split(",");
const params = linksArray.map((link) => ({
params: {
link: link.replace(".mdx", ""),
},
}));
return {
paths: params,
fallback: false,
};
} And providing data to each link using the export async function getStaticProps({ params }) {
const mdx = require("@mdx-js/mdx");
const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");
// Get File and get YAML data from markdown
const post = fs
.readFileSync(path.join("content", "posts/", `${params.link}.mdx`))
.toString();
const { data, content } = matter(post);
// Serialize date
const dateOptions = { year: "numeric", month: "long", day: "numeric" };
const formattedDate = data.date.toLocaleDateString("en-US", dateOptions);
// Make metadata
const frontMatter = {
...data,
date: formattedDate,
link: params.link,
};
const jsx = mdx.sync(content);
console.log(jsx);
return {
props: {
content: `# ${data.title}
\n<p className="date">${formattedDate}<p>
\n${content}`,
frontMatter,
},
};
} But I want to render my JSX which is generated from the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I'm also trying to achieve something very similar.
The official MDX doc seem to use a virtual file (need to dig in, may be the solution): I don't know if that helps, hope so! |
Beta Was this translation helpful? Give feedback.
-
@melvin2016 I have the same structure as you & this worked like a charm for me → #9524 (comment) I have a minimal repo if you want to have a look (images aren't working currently but I'm working on it) → https://github.com/deadcoder0904/blog-mdx-next/ |
Beta Was this translation helpful? Give feedback.
See https://github.com/hashicorp/next-mdx-remote