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