Logo
Published on

MDX Usage Guide: Features and Best Practices

Authors

MDX Usage Guide: Features and Best Practices

This document serves as a reference for creating and editing MDX files in our blog platform. It covers frontmatter configuration, markdown syntax, JSX components, and common pitfalls to avoid.

Frontmatter Configuration

Each MDX file requires YAML frontmatter at the beginning of the file, enclosed by three dashes (---):

---
title: "Your Post Title Here"  # Use double quotes if title contains apostrophes or quotes
date: '2025-03-20'             # ISO date format in single quotes
tags: ['markdown', 'guide']    # Array of tags in square brackets
draft: false                   # Boolean value (true/false without quotes)
summary: "A brief description of your post" # Keep under 160 characters
images: ['/static/images/your-image.png']  # Array of image paths
authors: ['default']           # Optional author references
---

Required Fields

  • title: The title of your post (use double quotes if it contains apostrophes or special characters)
  • date: Publication date in 'YYYY-MM-DD' format
  • tags: Array of relevant tags
  • draft: Boolean to indicate if the post is ready for publication
  • summary: Brief description of the content (recommended for SEO)
  • images: Array of image paths for thumbnails and social sharing

Optional Fields

  • authors: Array of author IDs
  • lastmod: Last modification date
  • layout: Custom layout (defaults to 'PostLayout')
  • bibliography: Path to bibliography file for citations
  • canonicalUrl: Original URL for syndicated content

Basic Markdown Syntax

MDX supports all standard Markdown syntax:

Headings

# Heading 1 (Page Title)
## Heading 2 (Section)
### Heading 3 (Sub-section)
#### Heading 4 (Topic)
##### Heading 5 (Sub-topic)
###### Heading 6 (Detail)

Formatting Text

**Bold text** or __Bold text__
*Italic text* or _Italic text_
~~Strikethrough text~~
`Inline code`

Lists

Unordered Lists

- Item 1
- Item 2
  - Nested item 2.1
  - Nested item 2.2
- Item 3

Ordered Lists

1. First item
2. Second item
   1. Nested item 2.1
   2. Nested item 2.2
3. Third item

Task Lists

- [x] Completed task
- [ ] Incomplete task
[Link text](https://example.com)
![Alt text for image](/static/images/example.png)

Code Blocks

MDX supports fenced code blocks with syntax highlighting:

```javascript
// This is a code block with JavaScript syntax highlighting
function greeting(name) {
  return `Hello, ${name}!`;
}
```

Code Block Features

// Syntax highlighting by specifying language
```python
def hello():
    print("Hello, world!")

// Adding a title to the code block

example.js
console.log('Hello');

// Line highlighting

import React from 'react';
import { Something } from './something';
function MyComponent() {
  return <Something />;
}

// Line numbers

<?php
echo "Hello, world!";
?>

## Blockquotes

```md
> This is a blockquote
> 
> It can span multiple lines

Callout Boxes (GitHub Style)

> [!NOTE]
> This is a note callout box

> [!TIP]
> This is a tip callout box

> [!WARNING]
> This is a warning callout box

> [!CAUTION]
> This is a caution callout box

Tables

| Header 1 | Header 2 | Header 3 |
|----------|----------|----------|
| Cell 1   | Cell 2   | Cell 3   |
| Cell 4   | Cell 5   | Cell 6   |

Math Equations

MDX supports LaTeX-style math equations:

Inline Math

The formula $E=mc^2$ is famous.

Block Math

$$
\frac{d}{dx}(e^x) = e^x
$$

Complex Equations

$$
\text{Model Performance} = \frac{\text{Quality of Data} \times \text{Algorithm Power}}{\text{Complexity} + \text{Bias}}
$$

JSX and React Components

MDX allows for embedding React components directly in your content:

Using Components

<CustomComponent prop1="value1" prop2={42}>
  Children content goes here
</CustomComponent>

<TOCInline toc={props.toc} />

Div Blocks with Classes

When you need custom styling or layout, you can use div elements with className:

<div className="bg-blue-50 p-6 rounded-lg my-6 border-l-4 border-blue-500">
  <p className="font-mono text-sm">
    This is a custom styled block with blue accent
  </p>
</div>

Image Best Practices

Standard Markdown Images

![Descriptive alt text for accessibility](/static/images/example.png)

Images With Captions

![Descriptive image alt text](/static/images/example.png)
*This is a caption for the image above*

Special Considerations and Pitfalls

1. Apostrophes and Quotes in Frontmatter

If your title or summary contains apostrophes or quotes, use double quotes to wrap the entire string:

title: "Don't Use Single Quotes for Strings with Apostrophes"
summary: "This is a \"quoted phrase\" within a summary"

2. Avoiding JSX Parsing Errors

Be careful with angle brackets < and > in your content, as they might be interpreted as JSX tags:

// INCORRECT - might cause parsing errors:
Generic<T> extends BaseClass<T>

// CORRECT - use code blocks or escape with HTML entities:
`Generic&lt;T&gt; extends BaseClass&lt;T&gt;`

3. HTML Tags in Text

When mentioning HTML tags in text, use code blocks or HTML entities:

// INCORRECT - will be parsed as actual HTML:
The <div> element is a container.

// CORRECT:
The `<div>` element is a container.
// OR
The &lt;div&gt; element is a container.

4. JSDoc in Code Examples

When showing JSDoc in code examples, avoid generic type parameters or escape them:

/**
 * @param {string} name - The name parameter
 * @returns {Promise} A promise that resolves
 */

File Organization

Our blog posts are organized in the following structure:

data/blog/
├── category-name/
│   ├── article-slug.mdx
│   └── another-article.mdx
├── uncategorized-article.mdx
└── another-top-level-article.mdx

Image Requirements

  • Use PNG format for all images
  • Place images in /static/images/ directory
  • Use descriptive filenames (e.g., data-flow-diagram.png not image1.png)
  • Include meaningful alt text for accessibility
  • Optimize images for web before uploading

MDX Processing

Our platform uses contentlayer2 to process MDX files with the following schema:

export const Blog = defineDocumentType(() => ({
  name: 'Blog',
  filePathPattern: 'blog/**/*.mdx',
  contentType: 'mdx',
  fields: {
    title: { type: 'string', required: true },
    date: { type: 'date', required: true },
    tags: { type: 'list', of: { type: 'string' }, default: [] },
    lastmod: { type: 'date' },
    draft: { type: 'boolean' },
    summary: { type: 'string' },
    images: { type: 'json' },
    authors: { type: 'list', of: { type: 'string' } },
    layout: { type: 'string' },
    bibliography: { type: 'string' },
    canonicalUrl: { type: 'string' },
  },
  computedFields: {
    // ...computed fields
  },
}))

Example Article Template

Below is a complete example of an MDX article incorporating various elements:

---
title: "Using MDX in Modern Web Development"
date: '2025-03-20'
tags: ['mdx', 'react', 'tutorial']
draft: false
summary: "Learn how to leverage MDX to create rich, interactive content that combines Markdown simplicity with React component power"
images: ['/static/images/mdx-example.png']
---

# Using MDX in Modern Web Development

## Introduction

MDX combines the **simplicity of Markdown** with the *power of JSX*. This allows you to use React components directly within your content.

> [!TIP]
> MDX is perfect for documentation, blogs, and content-heavy applications.

## Getting Started

Here's a simple React component used within MDX:

```jsx
function Greeting({ name }) {
  return <div>Hello, {name}!</div>;
}

<Greeting name="MDX User" />

Code Examples

// This is a code block with syntax highlighting
function calculateTotal(items) {
  return items.reduce((total, item) => total + item.price, 0);
}

Mathematical Expressions

The relationship between components and performance can be expressed as:

Performance=Component QualityBundle Size×Render Time\text{Performance} = \frac{\text{Component Quality}}{\text{Bundle Size} \times \text{Render Time}}

Data Tables

FeatureMarkdownMDX
Basic Syntax
Code Highlighting
React Components
Interactive Elements

Comparison of Markdown vs MDX capabilities Figure 1: Feature comparison between Markdown and MDX

Conclusion

MDX provides the perfect balance between developer experience and content authoring. By combining Markdown's simplicity with React's component model, it opens up new possibilities for interactive documentation and content.


## Additional Resources

For more information on MDX and its usage, refer to these resources:

- [Official MDX Documentation](https://mdxjs.com/)
- [Contentlayer Documentation](https://contentlayer.dev/)
- [React Markdown Guide](https://reactjs.org/markdown)

---

This guide was created to help content creators work effectively with MDX in our blog system. If you have questions or suggestions to improve this guide, please contact the development team.