---
title: "Shadcn Code Block"
description: "A soft, animated code block with a sliding file switcher, line numbers, line highlights and one-click copy. Free shadcn/ui Code Block animated with GSAP."
url: https://avaraui.com/docs/nextjs/code-block
---

# Shadcn Code Block

A soft, animated code block with a sliding file switcher, line numbers, line highlights and one-click copy.

## Installation

Add the component by URL — no setup needed:

```bash
npx shadcn@latest add https://avaraui.com/r/code-block.json
```

Or register the @avara-ui registry once per project and add it by name:

```bash
npx shadcn@latest registry add @avara-ui=https://avaraui.com/r/{name}.json
npx shadcn@latest add @avara-ui/code-block
```

## Code block

- Pass `code` as the raw source and `language` for the colours and icon.
- `maxLines` folds a long file behind a "show more" button. `0` shows it all.

```tsx
import { CodeBlock } from "@/components/custom/blocks/CodeBlock";

const tsx = `import { useEffect, useState } from "react";

interface SystemMetrics {
  ping: number;
  load: number;
}

export function SystemStatus({ serverName }: { serverName: string }) {
  const [metrics, setMetrics] = useState<SystemMetrics>({ ping: 45, load: 2.1 });

  useEffect(() => {
    // Simulate real-time monitoring data
    const interval = setInterval(() => {
      setMetrics({
        ping: Math.floor(Math.random() * 20) + 30,
        load: Number((Math.random() * 3 + 1).toFixed(2)),
      });
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div className="rounded-2xl bg-card p-6">
      <h3 className="text-xl font-semibold">{serverName}</h3>
      <p className="text-sm text-muted-foreground">
        {metrics.ping}ms ping, {metrics.load}% load
      </p>
    </div>
  );
}`;

export default function Snippet() {
  return <CodeBlock code={tsx} language="tsx" fileName="SystemStatus.tsx" />;
}
```

## Multiple files

- Pass `tabs` instead of `code`. One pill slides to the active file.

```tsx
import { CodeBlock } from "@/components/custom/blocks/CodeBlock";

const html = `<main class="app" id="app">
  <section class="card">
    <header class="card-header">
      <h2 class="title">Project Alpha</h2>
      <span class="badge">v2.4.1</span>
    </header>
    <p class="description">
      Deploy your applications to the edge in milliseconds.
    </p>
    <button class="btn" onclick="deploy()">Deploy now</button>
  </section>
</main>`;

const css = `:root {
  --primary: #6366f1;
  --surface: rgba(255, 255, 255, 0.1);
}

.card {
  background: var(--surface);
  backdrop-filter: blur(12px);
  border-radius: 16px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
}

.btn:hover {
  transform: translateY(-1px);
  transition: transform 300ms ease;
}`;

const tsx = `import { useEffect, useState } from "react";

interface SystemMetrics {
  ping: number;
  load: number;
}

export function SystemStatus({ serverName }: { serverName: string }) {
  const [metrics, setMetrics] = useState<SystemMetrics>({ ping: 45, load: 2.1 });

  useEffect(() => {
    // Simulate real-time monitoring data
    const interval = setInterval(() => {
      setMetrics({
        ping: Math.floor(Math.random() * 20) + 30,
        load: Number((Math.random() * 3 + 1).toFixed(2)),
      });
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div className="rounded-2xl bg-card p-6">
      <h3 className="text-xl font-semibold">{serverName}</h3>
      <p className="text-sm text-muted-foreground">
        {metrics.ping}ms ping, {metrics.load}% load
      </p>
    </div>
  );
}`;

export default function MultiFileSnippet() {
  return (
    <CodeBlock
      tabs={[
        { code: html, language: "html", fileName: "index.html" },
        { code: css, language: "css", fileName: "style.css" },
        { code: tsx, language: "tsx", fileName: "SystemStatus.tsx" },
      ]}
    />
  );
}
```

## Install commands

- Give each tab a `label` to switch package managers in one block.

```tsx
import { CodeBlock } from "@/components/custom/blocks/CodeBlock";

export default function InstallSnippet() {
  return (
    <CodeBlock
      language="bash"
      tabs={[
        { label: "npm", code: "npm install gsap" },
        { label: "pnpm", code: "pnpm add gsap" },
        { label: "yarn", code: "yarn add gsap" },
        { label: "bun", code: "bun add gsap" },
      ]}
    />
  );
}
```

## Highlights and diff

- Mark lines with `marks` as `add`, `remove` or `focus`, keyed by line number.

```tsx
import { CodeBlock } from "@/components/custom/blocks/CodeBlock";

const diff = `export function getGreeting(name: string) {
  const hour = new Date().getHours();
  return "Hello, " + name;
  const part = hour < 12 ? "morning" : "evening";
  return "Good " + part + ", " + name;
}`;

export default function DiffSnippet() {
  return (
    <CodeBlock
      code={diff}
      language="ts"
      fileName="greeting.ts"
      marks={{ 2: "focus", 3: "remove", 4: "add", 5: "add" }}
    />
  );
}
```

## Shell commands

- Use `language="bash"` for a `$` prompt and no line numbers.

```tsx
import { CodeBlock } from "@/components/custom/blocks/CodeBlock";

const shell = `# Create the app
npx create-next-app@latest my-app --typescript --tailwind
cd my-app

# Add the component and start the dev server
npx shadcn@latest registry add @avara-ui=https://avaraui.com/r/{name}.json
npm run dev`;

export default function ShellSnippet() {
  return <CodeBlock code={shell} language="bash" fileName="Terminal" />;
}
```

## About Shadcn Code Block

**What it is.** **Shadcn Code Block** (`CodeBlock`) is a single code viewer for docs, tutorials and install guides. It shows a file chip or a sliding file switcher, line numbers, line marks, folding and a copy button.

**How it is built.** A built-in tokenizer colours `js`/`ts`/`tsx`/`jsx`, `json`, `css`, `html`, `bash` and `python`, and renders plain React nodes, so no highlighter library and no site stylesheet is needed. The text colours follow light and dark mode, and the surface follows your theme tokens. Motion is GSAP: the header and lines blur in once on load, and again when you switch files or unfold.

**When to use it.** Use it wherever readers copy code. For a terminal window use [Terminal](https://avaraui.com/docs/nextjs/terminal).

## For AI agents

**When to use**

- Developer docs, tutorials, install steps and changelogs
- Several related files, or package-manager commands, behind one switcher

**When not to use**

- A terminal window with window chrome: use [Terminal](https://avaraui.com/docs/nextjs/terminal)
- Requests the reader can send and inspect: use [API Playground](https://avaraui.com/docs/nextjs/api-playground)

**Agent notes**

- `CodeBlock` takes `code`, `language` (default `"tsx"`) and `fileName`. Pass `tabs` instead of `code` for several files.
- A `tabs` item is `{ code, language?, fileName?, label?, marks? }`. `language` falls back to the block's `language`, and `label` overrides `fileName` on the tab.
- `marks` is `Record<number, "add" | "remove" | "focus">`, keyed by 1-based line number.
- Line numbers default to on, and off for shell snippets, which show a `$` prompt instead. Override with `showLineNumbers`.
- Files longer than `maxLines + 3` (default 16) fold. Unknown languages use the JavaScript rules.
- Copy always copies the raw source, without line numbers, marks or the `$` prompt.

## Props Reference

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `code` | `string` | - | The raw source for a single file. Ignored when `tabs` is not empty. |
| `language` | `string` | `"tsx"` | Picks the colours, the icon and the language label. Case-insensitive. |
| `fileName` | `string` | - | The label in the header chip. Without it the chip shows the language name. |
| `tabs` | `{ code: string; language?: string; fileName?: string; label?: string; marks?: Record<number, LineMark> }[]` | - | Groups several files behind one sliding-pill switcher. |
| `marks` | `Record<number, "add" \| "remove" \| "focus">` | - | Line marks for the single-file form, keyed by 1-based line number. |
| `showLineNumbers` | `boolean` | on, off for shell | Shows the line-number gutter. |
| `maxLines` | `number` | `16` | Lines shown before a long file folds. `0` never folds. |

## Works with other components

- Pair `CodeBlock` with [Terminal](https://avaraui.com/docs/nextjs/terminal) for command windows.
- Use [API Playground](https://avaraui.com/docs/nextjs/api-playground) for live request testing.
- Use [Copy Button](https://avaraui.com/docs/nextjs/copy-button) for standalone inline copy triggers.

## Does CodeBlock require Prism or Shiki?

No. It runs a small built-in tokenizer, so there is nothing to configure and no highlighter in your bundle. It colours tokens by pattern and does not parse the language the way Shiki does, so rare syntax may be coloured loosely.

## Which languages does CodeBlock highlight?

`js`, `jsx`, `ts`, `tsx`, `json`, `css`, `html` (and `xml`, `svg`), `bash` (and `sh`, `shell`, `zsh`), and `python`. `text` and `markdown` stay plain. Any other value uses the JavaScript rules.

## How do I show several files or package managers?

Pass `tabs`. Each tab needs `code`. Use `fileName` for file tabs or `label` for short names such as `npm` and `pnpm`. The icon, colours, language label and copy button follow the active tab, and the arrow keys, Home and End move between tabs.

## How do I highlight or diff lines?

Pass `marks` with 1-based line numbers: `add` and `remove` tint the line green or red and show a `+` or `−`, and `focus` adds a quiet tint. A tabbed block takes `marks` on each tab.

## What does the copy button copy?

The active file's raw `code`, with no line numbers, marks or shell prompt. It uses the Clipboard API and falls back to a hidden textarea on non-secure pages. The icon turns into a check for two seconds.

## Is it safe to show untrusted code?

Yes. Tokens are rendered as React text, never as injected HTML, so tags inside a snippet appear literally and do not run.

---

Live previews and every example: https://avaraui.com/docs/nextjs/code-block
