---
title: Code Block
description: A syntax-highlighting component capable of parsing Markdown fences, handling package manager tabs, and supporting adaptive themes
---

<ComponentPreview name="code-block-demo" />

## Installation

<Installation
  name="code-block"
  dependencies={["lucide-react", "prism-react-renderer"]}
/>

## Configuration

### Global CSS & Utilities

This component relies on specific CSS variables for its "surface" background logic (when not using the syntax theme's background) and utility classes for scrollbar management.

Add the following to your global CSS:

```css title="globals.css"
@layer base {
  :root {
    --surface: #fafafa; /* Light mode fallback */
  }

  .dark {
    --surface: #171717; /* Dark mode fallback */
  }
}

@layer utilities {
  /* Hides scrollbars for a cleaner aesthetic when interactions aren't required */
  .no-scrollbar::-webkit-scrollbar {
    display: none;
  }

  .no-scrollbar {
    -ms-overflow-style: none; /* IE and Edge */
    scrollbar-width: none; /* Firefox */
  }
}
```

## Usage

### Basic Code Rendering

Pass a raw string to the `code` prop. You can optionally add a `filename` to render a file header with an automatically resolved icon.

```tsx
import { CodeBlock } from "@/components/ui/code-block"

export default function Example() {
  return (
    <CodeBlock
      code={`console.log("Hello World")`}
      language="typescript"
      filename="app.ts"
      showLineNumbers
    />
  )
}
```

### Markdown String Parsing

The component includes a regex parser (`parseMarkdownCodeBlock`) that extracts the language and code from standard Markdown fence syntax. This is particularly useful when rendering content from an LLM or a CMS that returns raw markdown strings.

```tsx
// The language "python" is automatically extracted from the string
<CodeBlock
  code={`\`\`\`python
def hello():
    print("world")
\`\`\``}
/>
```

## Examples

### Markdown Integration

If your code string contains a markdown code fence (e.g., `typescript\n...\n`), the component can parse the language and content automatically.

<ComponentPreview name="code-block-markdown-string-demo" />

### MDX Transformer (Contentlayer/Fumadocs)

For documentation sites (like those using Contentlayer or Fumadocs), you can transform all native markdown `<pre>` blocks into the enhanced `CodeBlock` component.

```tsx title="mdx-components.tsx"
import type { MDXComponents } from "mdx/types"

import { CodeBlock } from "@/components/ui/code-block"

export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    ...components,
    pre: ({ children, ...props }) => {
      // Basic logic to extract code and language from markdown structure
      const code =
        typeof children === "object" && "props" in children
          ? children.props.children
          : ""

      const className =
        typeof children === "object" && "props" in children
          ? children.props.className || ""
          : ""
      const language = className.replace(/language-/, "")

      return (
        <CodeBlock
          code={code}
          language={language || "typescript"}
          showLineNumbers={true}
        />
      )
    },
  }
}
```

### Theme Background Toggle

Use `useThemeBackground={true}` to apply the specific background color defined within your Prism theme, overriding the default adaptive `--surface` variable.

<ComponentPreview name="code-block-python-demo" height="700px" />

### JSON Syntax Highlighting

Display formatted JSON data with syntax highlighting:

<ComponentPreview name="code-block-json-demo" height="700px" />

### Expandable Code Blocks

Handle long code snippets with expand/collapse functionality:

<ComponentPreview name="code-block-expand-demo" align="start" />

### Interactive Theme Demo

<ComponentPreview name="code-block-theme-demo" />

Cycle through Prism themes with background toggle to compare `bg-surface` vs. `useThemeBackground` behavior.

### NPX Commands

Handle package manager commands in markdown:

<ComponentPreview name="code-block-npx-markdown-demo" />

### Package Manager Commands

<ComponentPreview name="code-block-package-demo" />

## API Reference

### Props

| Prop                    | Type                                 | Default        | Description                                                                         |
| ----------------------- | ------------------------------------ | -------------- | ----------------------------------------------------------------------------------- |
| `code`                  | `string`                             | —              | The code content. Can be a raw string or a markdown fenced string.                  |
| `language`              | `string`                             | `"typescript"` | The language for syntax highlighting. Ignored if markdown fence detects a language. |
| `filename`              | `string`                             | —              | If provided, renders a header with a file icon.                                     |
| `showLineNumbers`       | `boolean`                            | `true`         | Toggles the line number gutter.                                                     |
| `expandable`            | `boolean`                            | `false`        | Enables the collapse/expand functionality.                                          |
| `defaultExpanded`       | `boolean`                            | `false`        | The initial state of the expandable block.                                          |
| `collapsedHeight`       | `string`                             | `"12rem"`      | CSS height value for the collapsed state.                                           |
| `theme`                 | `PrismTheme`                         | `undefined`    | A static Prism theme object.                                                        |
| `adaptiveTheme`         | `{ light, dark }`                    | —              | Object containing themes for light and dark modes.                                  |
| `useThemeBackground`    | `boolean`                            | `false`        | If true, applies the theme's background color. If false, uses `var(--surface)`.     |
| `npm`                   | `string`                             | —              | Command for npm tab.                                                                |
| `yarn`                  | `string`                             | —              | Command for yarn tab.                                                               |
| `pnpm`                  | `string`                             | —              | Command for pnpm tab.                                                               |
| `bun`                   | `string`                             | —              | Command for bun tab.                                                                |
| `defaultPackageManager` | `"npm" \| "yarn" \| "pnpm" \| "bun"` | `"npm"`        | The default active tab.                                                             |

### Background Behavior

- **Default (`useThemeBackground={false}`)**: Uses `bg-surface` CSS variable
- **Theme Background (`useThemeBackground={true}`)**: Uses `theme.plain.backgroundColor` from Prism theme
- Requires `--surface` CSS variable definition for default mode

### Types

```tsx
type PackageManager = "npm" | "yarn" | "pnpm" | "bun"

interface AdaptiveTheme {
  light: PrismTheme
  dark: PrismTheme
}
```

### Theme Structure

Custom themes follow the Prism theme structure:

```tsx
const customTheme: PrismTheme = {
  plain: {
    color: "#e6e6fa",
    backgroundColor: "#1a1a2e",
  },
  styles: [
    {
      types: ["comment"],
      style: {
        color: "#6a7b9a",
        fontStyle: "italic",
      },
    },
    // ... more styles
  ],
}
```
