Inserting React Components into Markdown: How to Use unified and MDX
Key point
This article introduces techniques for replacing custom tags in Gatsby Markdown with React components by leveraging the AST transformation principles of the unified library.
Details
To implement richer visual effects beyond basic Markdown syntax in technical blogs, this article covers methods for converting custom tags within Markdown files into React components. Specifically, it explains the process of converting Markdown to HTML using the unified library in a Gatsby environment, and proposes a method to reverse-engineer this by converting HTML back into a React tree.
The Conversion Process from Markdown to HTML
The core of converting Markdown to HTML lies in using the unified library. This process is divided into three stages, each passing through an Abstract Syntax Tree (AST).
- Markdown to mdast: Use
remark-parseto convert Markdown text into mdast (Markdown Abstract Syntax Tree). - mdast to hast: Convert mdast to hast (Hypertext Abstract Syntax Tree) via
remark-rehype. During this process, node types are changed to match HTML structures, such asheadingtypes becomingh2tags andemphasisbecomingemtags. - hast to HTML: Use
rehype-stringifyto assemble hast into the final HTML string.
Inserting React Components in Gatsby
Since Gatsby internally converts Markdown to HTML, it is difficult to directly intervene in the conversion process. Therefore, the approach used is to re-parse the HTML generated by Gatsby and replace it with React components.
- rehype-parse: Converts HTML strings into hast.
- rehype-react: Converts hast into React elements, mapping specific tag names (e.g.,
split-diff) to designated React components via thecomponentsoption. - Through this, custom tags written in Markdown, such as
<split-diff>, are replaced with actual React components and function during rendering.
Alternative Using MDX
A simpler method is to use MDX. MDX is a format that allows direct use of JSX within Markdown, using the .mdx extension.
- MDX works by compiling the written content into JavaScript and executing it at runtime.
- It is compatible with various frameworks that support JSX, such as Preact and Vue, in addition to React.
- In Next.js or Gatsby, you can integrate it by installing the
@next/mdxorgatsby-plugin-mdxplugins, respectively.
This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.
Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.