admin管理员组文章数量:1189837
I'm building a blog in React using MDX files, and I’ve run into an issue. I have several posts in MDX format, and I’d like to define metadata for them so I can perform search queries. Since MDX files aren’t directly queryable from a database, I’m unsure how to approach this.
Here’s an example of an MDX file:
---
title: "Hello World"
author: "Yasha"
date: "2025-01-24"
tags: ["React", "MDX"]
---
# Title
It's my first _post_! I'm really **EXCITED**.
<div className="flex">
<button className="bg-red-400">Hello</button>
<button>World</button>
</div>
And here’s my React component for rendering posts:
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { MDXProvider } from "@mdx-js/react";
import { readFile } from "node:fs/promises";
import { compile } from "@mdx-js/mdx";
import remarkFrontmatter from "remark-frontmatter";
import remarkMdxFrontmatter from "remark-mdx-frontmatter";
const Post = () => {
const { slug } = useParams();
const navigate = useNavigate();
const [PostComponent, setPostComponent] = useState<any>(null);
useEffect(() => {
const loadPost = async () => {
try {
// Check that the slug is valid and doesn't include slashes
const post = await import(`@/posts/${slug}.mdx`);
const { value } = await compile(await readFile(`@/posts/example.mdx`), {
jsx: true,
remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter],
});
console.log(value);
setPostComponent(() => post.default);
} catch (err) {
console.error("Post not found:", err);
setPostComponent(() => () => navigate("/notfound"));
}
};
if (slug) loadPost();
}, [slug]);
return (
<div className="container flex">
{PostComponent ? (
<MDXProvider>
<PostComponent />
</MDXProvider>
) : (
<p>Loading...</p>
)}
</div>
);
};
export default Post;
I’ve tried using frontmatter
for handling metadata, but it doesn’t seem to integrate well with TypeScript for type safety. I’ve also tried using gray-matter
and front-matter
, but they didn’t work as expected.
Could someone explain how to extract and use metadata properly? Is it possible to query MDX files from a backend and handle metadata differently to make this more scalable?
Thank you!
本文标签: javascriptHow to Extract and Use Metadata from MDX Files in a React BlogStack Overflow
版权声明:本文标题:javascript - How to Extract and Use Metadata from MDX Files in a React Blog? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738420524a2085836.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论