For AI agents: a documentation index is available at /llms.txt. Markdown versions are available at the same URL with .md appended, or by sending Accept: text/markdown. When the browser supports WebMCP (`document.modelContext`), this page also registers tools for profile, discovery, post search, projects, and same-origin navigation.

AkaraChen

How MDX Frontend Rendering Works

How MDX Frontend Rendering Works

This post breaks down an MDX frontend rendering approach in a React + Vite project. The approach compiles at runtime, and supports custom component mapping and code-block metadata.

1. Core dependencies

{
  "imports": {
    "@mdx-js/mdx": "npm:@mdx-js/mdx@^3.1.0",
    "@mdx-js/react": "npm:@mdx-js/react@^3.1.0",
    "rehype-mdx-code-props": "npm:rehype-mdx-code-props@^3.0.1"
  }
}
DependencyRole
@mdx-js/mdxMDX core compiler, provides runtime compilation
@mdx-js/reactReact integration, provides MDXProvider and component mapping
rehype-mdx-code-propsCode-block metadata plugin, supports attributes like filename

2. MDX compile config

File location: frontend/src/lib/mdx-config.ts

import { CompileOptions } from "@mdx-js/mdx";
import rehypeMdxCodeProps from "rehype-mdx-code-props";

export const mdxConfig: CompileOptions = {
  rehypePlugins: [
    [
      rehypeMdxCodeProps,
      {
        elementAttributeNameCase: "react",
        tagName: "pre",
      },
    ],
  ],
};

Config notes:

  • elementAttributeNameCase: "react": use React-style attribute names (className)
  • tagName: "pre": enable metadata parsing on <pre> tags

3. Core render component

File location: frontend/src/components/mdx/mdx-message.tsx

3.1 Full implementation

import React, { FC, Fragment, useEffect, useRef } from "react";
import { MDXProvider } from "@mdx-js/react";
import { evaluate } from "@mdx-js/mdx";
import { jsx } from "react/jsx-runtime";
import { useQuery } from "@tanstack/react-query";
import { mdxConfig } from "@/lib/mdx-config.ts";

// 自定义组件映射
const components = {
  // 代码相关
  code: InlineCode,
  pre: CodeBlock,

  // 标准 Markdown 元素
  h1: (p: any) => <h1 className="my-4 text-2xl font-bold" {...p} />,
  h2: (p: any) => <h2 className="my-3 text-xl font-semibold" {...p} />,
  h3: (p: any) => <h3 className="my-2 text-lg font-medium" {...p} />,
  p: (p: any) => <p className="my-2" {...p} />,
  a: (p: any) => (
    <a
      className="text-primary underline"
      target="_blank"
      rel="noreferrer"
      {...p}
    />
  ),
  strong: (p: any) => <strong className="font-semibold" {...p} />,
  em: (p: any) => <em className="italic" {...p} />,
};

// 带复制按钮的代码块
function CodeBlock({ children, className }: any) {
  const [copied, setCopied] = React.useState(false);
  const language = className?.replace("language-", "") || "text";
  const text = typeof children === "string" ? children : "";

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {}
  };

  return (
    <Card className="my-4 border">
      <CardHeader className="flex flex-row items-center justify-between py-2">
        <CardTitle className="font-mono text-xs lowercase">
          {language}
        </CardTitle>
        <Button
          size="icon"
          variant="ghost"
          onClick={copy}
          className="h-6 w-6"
        >
          <Copy className="h-3 w-3" />
        </Button>
      </CardHeader>
      <CardContent className="p-0">
        <pre className="overflow-x-auto p-4 text-sm">
          <code className={className}>{children}</code>
        </pre>
      </CardContent>
    </Card>
  );
}

// 内联代码样式
function InlineCode(props: any) {
  return <code className="bg-muted rounded px-1 text-sm" {...props} />;
}

// 主渲染组件
export default function MdxMessage({ mdx, className = "" }: Props) {
  // 使用 React Query 缓存编译结果
  const render = useQuery({
    queryKey: ["mdx", mdx],
    queryFn: () =>
      evaluate(mdx, {
        ...mdxConfig,
        Fragment,
        jsx,
        jsxs: jsx,
        useMDXComponents: () => components,
      }).then((result) => result.default),
  });

  // 保持最新渲染结果,避免编译过程中的闪烁
  const latestMDX = useRef<FC | null>(null);
  useEffect(() => {
    if (render.data && !render.isError) {
      latestMDX.current = render.data;
    }
  }, [render.data, render.isError]);

  return (
    <MDXProvider components={components}>
      <div className={`prose prose-sm dark:prose-invert max-w-none ${className}`}>
        {latestMDX.current && <latestMDX.current />}
      </div>
    </MDXProvider>
  );
}

3.2 Key implementation logic

TechniqueHowWhat it does
Runtime compileevaluate()Dynamically compile an MDX string in the browser
CacheReact Query queryKeySame content compiles once
Anti-flickeruseRef holds the resultKeep showing old content while compiling
Component injectuseMDXComponentsProvide custom component mapping

4. Component mapping

const components = {
  // 代码相关
  code: InlineCode,
  pre: CodeBlock,

  // 标题
  h1: (p: any) => <h1 className="my-4 text-2xl font-bold" {...p} />,
  h2: (p: any) => <h2 className="my-3 text-xl font-semibold" {...p} />,
  h3: (p: any) => <h3 className="my-2 text-lg font-medium" {...p} />,

  // 文本
  p: (p: any) => <p className="my-2" {...p} />,
  strong: (p: any) => <strong className="font-semibold" {...p} />,
  em: (p: any) => <em className="italic" {...p} />,
  code: InlineCode,

  // 链接
  a: (p: any) => (
    <a
      className="text-primary underline"
      target="_blank"
      rel="noreferrer"
      {...p}
    />
  ),
};

5. Render flow

MDX 字符串
    ↓
evaluate() 编译为 React 组件
    ↓
MDXProvider 注入自定义组件映射
    ↓
React 渲染最终 UI

6. Supported MDX syntax

Standard Markdown

# 一级标题
## 二级标题
### 三级标题

**加粗文本** *斜体文本* `内联代码`

[链接文字](https://example.com)

Code blocks (with metadata)

```javascript {filename="app.js" copy}
const greeting = "Hello, MDX!";
console.log(greeting);

With the `rehype-mdx-code-props` plugin, you can add metadata attributes on code blocks:
- `filename`: filename
- `copy`: show a copy button

## 7. Performance

1. **React Query cache**: the same MDX content compiles once
2. **Anti-flicker**: use `useRef` to keep the latest render result
3. **Render on demand**: only update the display when `render.data` exists

## 8. File locations

frontend/src/ ├── lib/ │ └── mdx-config.ts # MDX 编译配置 └── components/ └── mdx/ └── mdx-message.tsx # 核心 MDX 渲染组件