Code Blocks
Code blocks are a fundamental part of any documentation site. This template provides a CodeBlock component with copy-to-clipboard functionality, optional filenames, and language labels.
Overview
The CodeBlock component wraps code content in a styled container with a header showing the filename or language, and a copy button that provides visual feedback upon copying.
Basic code block
A simple code block with a language label:
typescript
interface User {
id: string
name: string
email: string
role: "admin" | "user" | "viewer"
}
function getUser(id: string): Promise<User> {
return fetch(`/api/users/${id}`).then(res => res.json())
}With filename
Pass a filename prop to display the file path in the header:
lib/auth.ts
import { cookies } from "next/headers"
import { verify } from "jsonwebtoken"
export async function getSession() {
const cookieStore = await cookies()
const token = cookieStore.get("session")?.value
if (!token) return null
try {
return verify(token, process.env.JWT_SECRET!)
} catch {
return null
}
}Multiple languages
Code blocks work with any language. Here are some examples:
styles.css
:root {
--background: oklch(0.995 0 0);
--foreground: oklch(0.13 0 0);
--accent: oklch(0.55 0.15 250);
}
.docs-prose h1 {
font-size: 1.875rem;
font-weight: 700;
letter-spacing: -0.025em;
}docker-compose.yml
version: "3.8"
services:
app:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgresql://localhost:5432/docs
volumes:
- .:/app
- /app/node_modulesbash
# Clone the repository git clone https://github.com/your-org/docs-template.git # Install dependencies cd docs-template && bun install # Start development server bun run dev
Inline code
For inline code references, use standard code tags styled via the docs-prose CSS class. For example, referencing useState or next.config.mjs within paragraph text.
Component usage
Import and use the
CodeBlock component in any page or component. It accepts children (the code string), language, and filename props.Usage example
import { CodeBlock } from "@/components/docs/code-block"
export function MyPage() {
return (
<CodeBlock filename="hello.ts" language="typescript">
{`const greeting = "G'day, world!"`}
</CodeBlock>
)
}