Choose Theme

MDX Features Demo

· 5 min read
--

MDX Features Demo

This page demonstrates all available MDX components and enhanced code block features.

Alerts

Alerts come in different variants to highlight important information.

ℹ️

This is an info alert. Use it for general information that users should know.

This is a success alert. Perfect for confirming successful operations or positive outcomes.

⚠️

This is a warning alert. Use it to warn users about potential issues or things to watch out for.

This is an error alert. Use it for critical errors or issues that need immediate attention.

Callouts

Callouts are great for highlighting specific types of content.

ℹ️
Note

This is a note callout. Use it for additional information or clarifications.

💡
Tip

This is a tip callout. Share helpful tips and best practices here.

Important

This is an important callout. Use it to draw attention to critical information.

⚠️
Warning

This is a warning callout. Warn users about potential pitfalls or issues.

🚨
Caution

This is a caution callout. Use it for things that require extra care or attention.

Badges

Use badges for inline tags and labels: TypeScript Astro MDX Important

Code Block Features

Basic Code Block with Line Numbers

function greet(name: string): string {
return `Hello, ${name}!`;
}
const message = greet('World');
console.log(message);

Code Block with Filename

utils/greet.ts
export function greet(name: string): string {
return `Hello, ${name}!`;
}

Line Highlighting

Highlight specific lines to draw attention to important code:

function calculateTotal(items: Item[]): number {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
const tax = subtotal * 0.1;
const shipping = subtotal > 100 ? 0 : 10;
const discount = subtotal > 200 ? 20 : 0;
const total = subtotal + tax + shipping - discount;
return total;
}

Diff Markers (Added Lines)

Show code additions with diff markers:

function authenticate(user: User): boolean {
if (!user.email || !user.password) {
return false;
}
// [!code ++]
// Add email verification check
if (!user.emailVerified) {
throw new Error('Please verify your email first');
}
// [!code ++]
return validateCredentials(user);
}

Diff Markers (Removed Lines)

Show code removals with diff markers:

function fetchData(url: string): Promise<Data> {
// [!code --]
// Old implementation using fetch
return fetch(url).then(res => res.json());
// [!code --]
// [!code ++]
// New implementation with error handling
return fetch(url)
.then(res => {
if (!res.ok) throw new Error('Network error');
return res.json();
})
.catch(err => {
console.error('Fetch failed:', err);
throw err;
});
// [!code ++]
}

Complex Example

Combining filename, line highlighting, and diff markers:

api/users.ts
import { supabase } from '../db/supabase';
export async function getUser(id: string) {
// [!code --]
const { data } = await supabase
.from('users')
.select('*')
.eq('id', id);
// [!code --]
// [!code ++]
const { data, error } = await supabase
.from('users')
.select('id, email, name, created_at')
.eq('id', id)
.single();
if (error) {
throw new Error(`Failed to fetch user: ${error.message}`);
}
// [!code ++]
return data;
}

Multiple Languages

JavaScript

const users = ['Alice', 'Bob', 'Charlie'];
const greetings = users.map(user => `Hello, ${user}!`);
console.log(greetings);

Python

def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))

Rust

fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let sum: i32 = numbers.iter().sum();
println!("Sum: {}", sum);
}

SQL

CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_users_email ON users(email);

Links have a subtle underline style: Astro documentation, MDX Guide, and Tailwind CSS.

You can also reference internal pages like the homepage, other posts, or shorts.

Inline Code

You can also use inline code like const x = 42 or import { Component } from 'astro' within your text.

Combining Everything

Here’s a real-world example combining multiple features:

💡
Tip

The following code shows how to implement a custom hook with proper TypeScript typing and error handling.

hooks/useLocalStorage.ts
import { useState, useEffect } from 'react';
export function useLocalStorage<T>(key: string, initialValue: T) {
// [!code --]
const [value, setValue] = useState<T>(initialValue);
// [!code --]
// [!code ++]
const [value, setValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(`Error loading ${key} from localStorage:`, error);
return initialValue;
}
});
// [!code ++]
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Error saving ${key} to localStorage:`, error);
}
}, [key, value]);
return [value, setValue] as const;
}

You now have access to all these powerful MDX features! Use them to create engaging, informative content.


Summary

This demo showcases:

  • Alerts - 4 variants (info, success, warning, error)
  • Callouts - 5 types (note, tip, important, warning, caution)
  • Badges - Inline colored labels
  • Code Blocks - Line numbers, highlighting, diffs, and more

All of these components are available in your MDX files!