MDX Features Showcase - Interactive Components & Advanced Controls
MDX Features Showcase
Welcome to the MDX Features Showcase! This post demonstrates the powerful interactive components and advanced features that make MDX far superior to regular Markdown.
Why MDX is Better Than Markdown
1. Interactive Components 🎯
Unlike plain Markdown, MDX allows you to embed fully interactive React components:
2. Rich Alert System 🚨
MDX supports multiple alert types with custom styling:
Advanced Features
Collapsible Sections with Expandable 📦
One of the most powerful features is the ability to hide complex content behind expandable sections:
This content is hidden by default and only shown when the user clicks to expand it. This is perfect for:
- Long code examples that might overwhelm readers
- Technical details that advanced users want but beginners can skip
- Additional resources that are optional
- Troubleshooting steps that most users won't need
// Example: Complex code that you might want to hide
function complexAlgorithm(data) {
return data
.filter(item => item.active)
.map(item => ({
...item,
processed: true,
timestamp: Date.now()
}))
.reduce((acc, curr) => {
acc[curr.id] = curr;
return acc;
}, {});
}
This keeps your posts clean and scannable while still providing depth for those who want it!
Here's how you might use expandable sections for installation instructions:
-
Install dependencies
npm install @next/mdx @mdx-js/loader @mdx-js/react -
Configure next.config.js
const withMDX = require('@next/mdx')({ extension: /\.mdx?$/, }); module.exports = withMDX({ pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'], }); -
Create your first MDX file
# Hello MDX! <CustomComponent />
Embedded Media
YouTube Videos 📺
MDX makes it trivial to embed YouTube videos with a custom component:
With plain Markdown, you'd need to write raw HTML or use a complex iframe. With MDX, it's just one clean component!
Responsive Images 🖼️
The Image component provides automatic responsive behavior with captions:
This image automatically adapts to different screen sizes with beautiful styling
Code Syntax Highlighting
MDX supports full syntax highlighting for code blocks, just like Markdown:
// TypeScript example with full syntax highlighting
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user' | 'guest';
}
async function fetchUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error('Failed to fetch user');
}
return response.json();
}
# Python example
def fibonacci(n: int) -> list[int]:
"""Generate Fibonacci sequence up to n terms."""
if n <= 0:
return []
elif n == 1:
return [0]
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[i-1] + sequence[i-2])
return sequence
print(fibonacci(10))
Combining Features
The real power comes from combining multiple features:
Here's how you might document a complex feature:
Step 1: Setup
npm install my-awesome-library
Step 2: Configuration
{
"version": "1.0.0",
"features": {
"analytics": true,
"darkMode": true
}
}
Step 3: Usage
import { MyComponent } from 'my-awesome-library';
export default function App() {
return <MyComponent theme="dark" />;
}
Comparison: Markdown vs MDX
| Feature | Markdown | MDX | |---------|----------|-----| | Basic formatting (bold, italic, lists) | ✅ Yes | ✅ Yes | | Code syntax highlighting | ✅ Yes | ✅ Yes | | Images | ✅ Yes | ✅ Yes (with enhanced components) | | Interactive components | ❌ No | ✅ Yes | | Custom alerts/callouts | ⚠️ Limited (via HTML) | ✅ Yes (native components) | | Collapsible sections | ❌ No | ✅ Yes | | Embedded videos | ⚠️ Via raw HTML | ✅ Yes (clean components) | | Dynamic content | ❌ No | ✅ Yes | | Reusable components | ❌ No | ✅ Yes | | Type safety | ❌ No | ✅ Yes (with TypeScript) |
Best Practices for MDX
Don't overuse interactive components. They should enhance your content, not overwhelm it.
Good: Using an Alert to highlight a critical security warning Bad: Wrapping every paragraph in an Alert component
Ensure your components work well with:
- Screen readers
- Keyboard navigation
- Different screen sizes
- Light and dark modes
Use Expandable sections to:
- Hide optional advanced content
- Reduce initial page complexity
- Let readers choose their depth level
- Keep the main narrative focused
Always consider what happens if:
- JavaScript is disabled
- Components fail to load
- Images don't load
- Videos are blocked
Real-World Use Cases
Technical Documentation
Endpoint: POST /api/users
Request Body:
{
"name": "John Doe",
"email": "[email protected]",
"role": "user"
}
Response:
{
"id": "usr_123abc",
"name": "John Doe",
"email": "[email protected]",
"role": "user",
"createdAt": "2024-11-25T12:00:00Z"
}
Tutorials & Guides
Step 1: Create the component file
// components/Button.tsx
interface ButtonProps {
label: string;
onClick: () => void;
}
export default function Button({ label, onClick }: ButtonProps) {
return (
<button onClick={onClick} className="btn">
{label}
</button>
);
}
Step 2: Style your component
.btn {
padding: 0.5rem 1rem;
border-radius: 0.25rem;
background: #007bff;
color: white;
border: none;
cursor: pointer;
}
Step 3: Use it in your app
import Button from './components/Button';
export default function App() {
return (
<Button
label="Click me!"
onClick={() => alert('Hello!')}
/>
);
}
Conclusion
MDX transforms static Markdown into an interactive, component-driven format that's perfect for modern web content. The key advantages are:
Ready to start using MDX? Here's what to do next:
- Explore the Components - Check out the source code for Alert, Expandable, YouTube, and Image components
- Create Your First MDX Post - Use this post as a template
- Build Custom Components - Create your own interactive components for your specific needs
- Share Your Work - Show the community what you've built with MDX!
Happy writing with MDX! 🚀✨