MDX와 리액트
Docusaurus has built-in support for MDX, which allows you to write JSX within your Markdown files and render them as React components.
Check out the MDX docs to see what fancy stuff you can do with MDX.
The MDX format is quite strict, and you may get compilation errors.
Use the MDX playground to debug them and make sure your syntax is valid.
Exporting components
To define any custom component within an MDX file, you have to export it: only paragraphs that start with export
will be parsed as components instead of prose.
export const Highlight = ({children, color}) => (
<span
style={{
backgroundColor: color,
borderRadius: '2px',
color: '#fff',
padding: '0.2rem',
}}>
{children}
</span>
);
<Highlight color="#25c2a0">Docusaurus green</Highlight> and <Highlight color="#1877F2">Facebook blue</Highlight> are my favorite colors.
I can write **Markdown** alongside my _JSX_!
Notice how it renders both the markup from your React component and the Markdown syntax:
I can write Markdown alongside my JSX!
Since all doc files are parsed using MDX, anything that looks like HTML is actually JSX. Therefore, if you need to inline-style a component, follow JSX flavor and provide style objects.
/* Instead of this: */
<span style="background-color: red">Foo</span>
/* Use this: */
<span style={{backgroundColor: 'red'}}>Foo</span>
Importing components
You can also import your own components defined in other files or third-party components installed via npm.
<!-- Docusaurus theme component -->
import TOCInline from '@theme/TOCInline';
<!-- External component -->
import Button from '@mui/material/Button';
<!-- Custom component -->
import BrowserWindow from '@site/src/components/BrowserWindow';
The @site
alias points to your website's directory, usually where the docusaurus.config.js
file is. Using an alias instead of relative paths ('../../src/components/BrowserWindow'
) saves you from updating import paths when moving files around, or when versioning docs and translating.
While declaring components within Markdown is very convenient for simple cases, it becomes hard to maintain because of limited editor support, risks of parsing errors, and low reusability. Use a separate .js
file when your component involves complex JS logic:
import React from 'react';
export default function Highlight({children, color}) {
return (
<span
style={{
backgroundColor: color,
borderRadius: '2px',
color: '#fff',
padding: '0.2rem',
}}>
{children}
</span>
);
}
import Highlight from '@site/src/components/Highlight';
<Highlight color="#25c2a0">Docusaurus green</Highlight>