MDX Notes
Multi-language code tabs, npm2yarn auto-conversion, the CodeBlock component, live editors, line highlighting, and magic comments
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import CodeBlock from '@theme/CodeBlock';
Code examples are the heart of technical docs. Docusaurus gives you a lot of tools here — tabbed multi-language blocks, live editable code, line highlighting, file name headers, and magic comments that control highlighting from inside the code itself.
Multi-Language Code Examples with Tabs
The bread and butter: show the same thing in JavaScript, TypeScript, and Python side by side.
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs groupId="language">
<TabItem value="js" label="JavaScript">function greet(name) { return Hello, ${name}!; }
module.exports = { greet };
</TabItem>
<TabItem value="ts" label="TypeScript">function greet(name: string): string { return Hello, ${name}!; }
export { greet };
</TabItem>
<TabItem value="python" label="Python">def greet(name: str) -> str: return f"Hello, {name}!"
</TabItem>
</Tabs>Visual Result: Three language tabs with syntax-highlighted code. Click a tab, see that language's version.
The npm/yarn/pnpm Tabs Pattern
Every JS doc needs this. Here's two ways to do it.
Manual Approach
<Tabs groupId="package-manager">
<TabItem value="npm" label="npm">npm install react react-dom
</TabItem>
<TabItem value="yarn" label="Yarn">yarn add react react-dom
</TabItem>
<TabItem value="pnpm" label="pnpm">pnpm add react react-dom
</TabItem>
</Tabs>Automatic with npm2yarn Plugin
Or skip the manual work entirely. Docusaurus has a plugin that auto-generates Yarn and pnpm equivalents from npm commands:
Install it first:
npm install @docusaurus/remark-plugin-npm2yarnThen just write npm commands with the npm2yarn meta tag:
npm install @docusaurus/core @docusaurus/preset-classic
Visual Result: Docusaurus auto-creates tabs showing npm, Yarn, and pnpm equivalents. You only wrote the npm version.
:::tip[Sync Across Pages] The { sync: true } option means when a user picks "Yarn" on one page, every npm2yarn tab across your whole site switches to Yarn. It uses localStorage. :::
The CodeBlock Component
When you need to render code dynamically (from a variable, prop, or imported file), use the CodeBlock component directly:
import CodeBlock from '@theme/CodeBlock';
<CodeBlock language="jsx" title="src/components/Hello.jsx" showLineNumbers>
{`import React from 'react';
export default function Hello({ name }) {
return <h1>Hello, {name}!</h1>;
}`}
</CodeBlock>CodeBlock Props
| Prop | Type | Description |
|---|---|---|
language | string | Syntax highlighting language |
title | string | File name/path displayed above code |
showLineNumbers | boolean | Show line numbers |
metastring | string | Same as code fence meta (for highlighting) |
Dynamic Code with CodeBlock
This is useful when code content comes from a variable:
export const configExample = `module.exports = {
title: '${siteTitle}',
url: '${siteUrl}',
};`;
<CodeBlock language="js" title="docusaurus.config.js">
{configExample}
</CodeBlock>Importing Code from Files
You can pull in actual source files and display them:
import MyComponent from '!!raw-loader!./src/components/MyComponent.jsx';
<CodeBlock language="jsx" title="src/components/MyComponent.jsx" showLineNumbers>
{MyComponent}
</CodeBlock>:::note The !!raw-loader! prefix tells Webpack to load the file as raw text instead of executing it. This is built into Docusaurus — no extra config needed. :::
Live Code Editor
Want readers to edit code and see results in real-time? Install the live codeblock theme:
Setup
npm install @docusaurus/theme-live-codeblockUsing Live Code Blocks
Add live to any JSX code fence:
function Clock() { const [date, setDate] = React.useState(new Date());
React.useEffect(() => { const timer = setInterval(() => { setDate(new Date()); }, 1000); return () => clearInterval(timer); }, []);
return ( <div style={{ padding: '20px', background: '#282c34', color: '#61dafb', borderRadius: '8px', fontFamily: 'monospace', fontSize: '24px', textAlign: 'center', }}> ⏰ {date.toLocaleTimeString()} </div> ); }
Visual Result: An editable text area with a live preview below it. Edit the code, the preview updates instantly. Errors show inline.
Live Editor with noInline
For code that needs an explicit render() call:
const Greeting = ({ name }) => ( <div style={{ color: 'coral', fontSize: '24px' }}> Hello, {name}! 👋 </div> );
render(<Greeting name="Docusaurus Developer" />);
:::caution[Live Editor Limitations]
- Only works with React/JSX code
- Cannot import external modules (only React is available in scope)
- Code must be self-contained
- Not suitable for Node.js or backend code examples
:::
Highlighting Lines
You can highlight specific lines to draw attention to what matters.
Using Line Numbers in Meta String
const config = { // highlight-next-line title: 'My Amazing Site', // Line 2 highlighted url: 'https://example.com', baseUrl: '/', onBrokenLinks: 'throw', // Lines 5-7 highlighted onBrokenMarkdownLinks: 'warn', favicon: 'img/favicon.ico', };
Range Syntax
| {1} | highlight line 1 |
| {1,3} | highlight lines 1 and 3 |
| {1-4} | highlight lines 1 through 4 |
| {1,3-5,8} | highlight lines 1, 3 through 5, and 8 |
Showing File Names
Add a title to show a filename header above the code:
{ "name": "my-docusaurus-site", "version": "1.0.0", "scripts": { "start": "docusaurus start", "build": "docusaurus build" } }
Visual Result: A header bar above the code block showing "package.json" — looks like a code editor tab.
Magic Comments
These are inline comments that control highlighting without touching the meta string. Really useful when line numbers might shift as you edit:
const name = 'Docusaurus';
// highlight-next-line const highlighted = 'This line is highlighted';
// highlight-start const alsoHighlighted = 'This line too'; const andThisOne = 'And this one'; // highlight-end
const normal = 'Back to normal';
Available Magic Comments
| Comment | Effect |
|---|---|
// highlight-next-line | Highlights the next line |
// highlight-start | Begins a highlighted block |
// highlight-end | Ends a highlighted block |
// highlight-error-next-line | Highlights next line in red (error) |
Magic Comments in Different Languages
The comment syntax adapts to whatever language you're in:
highlight-next-line
important_value = calculate_result()
<!-- highlight-next-line --> <div class="highlighted">This div is highlighted</div>
/* highlight-next-line */ .highlighted { color: red; }
Custom Magic Comments
You can define your own keywords — useful for showing diffs (added/removed lines):
.code-block-added-line {
background-color: rgba(0, 255, 0, 0.1);
border-left: 3px solid #00ff00;
}
.code-block-removed-line {
background-color: rgba(255, 0, 0, 0.1);
border-left: 3px solid #ff0000;
text-decoration: line-through;
}Then in your docs:
const config = { // remove-next-line oldSetting: true, // add-next-line newSetting: 'better', };
Line Numbers
Turn on line numbers for any block:
const line1 = 'first'; const line2 = 'second'; const line3 = 'third';
Start from a specific number (useful for showing a snippet from a larger file):
// This starts at line 42 const answer = 'to everything';
Prism Language Support
Need syntax highlighting for Rust, Go, or Kotlin? Add them in your config:
Best Practices for Code in Documentation
:::tip[Code Documentation Tips]
- Always add
title— File paths help readers know where code belongs - Use
groupId— Sync language preferences across the entire doc site - Highlight sparingly — Only highlight lines that are new or important
- Prefer magic comments — They're more maintainable than line number ranges
- Use npm2yarn — Don't manually write three package manager variants
- Include context — Show enough surrounding code for readers to orient themselves
- Test live blocks — Always verify live code blocks actually render correctly
:::
Code is the most important thing in technical docs. If your code examples are hard to read, nothing else matters. Docusaurus gives you all the tools to make them clear, interactive, and easy to copy. Use them.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Code Tabs and CodeBlock in Docusaurus.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this MDX Tutorial topic.
Search Terms
mdx-tutorial, mdx tutorial, mdx, tutorial, docusaurus, code, tabs, code tabs and codeblock in docusaurus
Related MDX Tutorial Topics