---
title: "Code Block"
description: "A syntax-highlighted code surface with stable streaming updates, line numbers, focused lines, smooth following, and copy feedback."
category: "AI Agents"
publishedAt: "2026-08-02"
updatedAt: "2026-11-25"
documentation: "https://beui.dev/components/agents/code-block"
markdown: "https://beui.dev/components/agents/code-block.md"
license: "MIT"
---

# Code Block

> A syntax-highlighted code surface with stable streaming updates, line numbers, focused lines, smooth following, and copy feedback.

## Install

```bash
npx shadcn@latest add @beui/code-block
```

## Dependencies

- `@floating-ui/dom`
- `ai`
- `clsx`
- `lucide-react`
- `motion`
- `react`
- `react-dom`
- `shiki`
- `tailwind-merge`

## Usage

```tsx
"use client";

import { RotateCcw } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { CodeBlock } from "@/components/agents/code-block";

const LINES = [
  'import { generateText } from "ai";',
  "",
  "export async function summarize(input: string) {",
  "  const { text } = await generateText({",
  '    model: "openai/gpt-5",',
  `    prompt: \`Summarize this clearly: \${input}\`,`,
  "  });",
  "",
  "  return {",
  "    text,",
  "    generatedAt: new Date().toISOString(),",
  "  };",
  "}",
];

function StreamingCodeBlock() {
  const [visibleLines, setVisibleLines] = useState(1);
  const timer = useRef<number | undefined>(undefined);
  const complete = visibleLines === LINES.length;

  useEffect(() => {
    if (visibleLines >= LINES.length) return;
    timer.current = window.setTimeout(
      () => setVisibleLines((value) => value + 1),
      260,
    );
    return () => {
      if (timer.current) window.clearTimeout(timer.current);
    };
  }, [visibleLines]);

  return (
    <CodeBlock
      filename="summarize.ts"
      language="typescript"
      code={LINES.slice(0, visibleLines).join("\n")}
      status={complete ? "complete" : "streaming"}
      highlightLines={[4, 5, 6, 7]}
      maxHeight={224}
    />
  );
}

export function CodeBlockPreview() {
  const [run, setRun] = useState(0);

  return (
    <div className="relative h-[340px] w-full max-w-xl">
      <StreamingCodeBlock key={run} />
      <button
        type="button"
        onClick={() => setRun((value) => value + 1)}
        className="absolute bottom-0 left-0 inline-flex items-center gap-1.5 rounded-full px-2 py-1 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
      >
        <RotateCcw className="size-3" />
        Replay
      </button>
    </div>
  );
}
```

## API Reference

### CodeBlock

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `code` | `string` |  | Yes | The source code to show. May grow while `status` is "streaming". |
| `language` | `"text" \| "bash" \| "diff" \| "json" \| "tsx" \| "typescript"` | `typescript` | No | Language for syntax highlighting, also shown in the header. Default: "typescript" |
| `filename` | `ReactNode` |  | No | File name shown in the header. |
| `status` | `"streaming" \| "complete"` | `complete` | No | "streaming" shows Writing and follows new lines, "complete" shows Ready. Default: "complete" |
| `showLineNumbers` | `boolean` | `true` | No | Shows a line number gutter. Default: true |
| `highlightLines` | `number[]` | `[]` | No | 1-based line numbers to tint. |
| `maxHeight` | `number` | `280` | No | Height in px before the code scrolls. Default: 280 |
| `wrap` | `boolean` | `false` | No | Wraps long lines instead of scrolling sideways. Default: false |
| `copyable` | `boolean` | `true` | No | Shows the copy button. Default: true |
| `onCopy` | `(() => void \| Promise<void>)` |  | No | Runs in place of the clipboard write when copy is pressed. Shows the copy button. |
| `className` | `string` |  | No | Classes merged onto the root element. |
| `labels` | `Partial<{ writing: string; ready: string; copy: string; copied: string; }>` |  | No | Override any built-in string. |

## Composition

Nest generated source inside the response that owns its streaming lifecycle.

```text
StreamingResponse
└── CodeBlock
```

- `file-diff`: Explains additions and removals around highlighted code.
- `tool-result`: Wraps generated code in an execution outcome.
- `streaming-response`: Embeds highlighted code inside a rich answer.

### How it works

Generated code changes faster than a conventional static snippet. The surface must remain readable while lines arrive, preserve syntax structure, and make copying the final result predictable.

- **Receive.** Source text may arrive incrementally without changing the surrounding block.
- **Highlight.** Tokens, line numbers, and focused ranges update as stable visual layers.
- **Finalize.** Following stops at completion and the complete source becomes ready to copy.

### What it owns and what it leaves to you

- **Owns:** Highlighted presentation, line numbers, focused ranges, streaming follow behavior, and copy feedback.
- **Leaves to the app:** Code generation, language detection policy, execution, and file persistence to the application.

### Principles

- **Highlight complete units.** Token colors should update without flashing the entire block. Partial input remains legible until the current language structure is complete.
- **Keep lines addressable.** Line numbers and focused ranges give discussions a stable reference even when only part of the file is emphasized.
- **Follow without flicker.** A bounded viewport follows appended lines smoothly while the code background and existing rows remain fixed.

### Use it when

Generated or retrieved source needs syntax highlighting, line references, streaming, or focused ranges.

### Avoid it when

You need to explain file changes with additions and removals; use a file diff for that relationship.

## About Code Block

Code Block is a syntax highlighted code viewer for AI chat and agent interfaces in React. It highlights with Shiki, keeps line rows stable while code streams in, follows the newest lines inside a capped height, and switches from a Writing badge to Ready when the code is complete. It supports line numbers, highlighted lines, a filename, wrapping and a copy button with confirmation feedback.

### When to use it

- An AI coding assistant writes a function into the chat and the reader watches it arrive line by line.
- An agent response cites a specific part of a file and needs to highlight those lines.
- A chat app shows a shell command or JSON payload the user can copy in one click.

### Accessibility

While streaming, the container is marked aria-busy and the code viewport becomes a polite log region, and both return to normal when the code is complete. The copy button is labeled "Copy code" and changes to "Copied" after copying, and line numbers cannot be selected, so manual copying takes only code. With reduced motion enabled, the streaming spinner stops and auto following jumps instead of scrolling smoothly.

### FAQ

**How do I show streaming code from an LLM in React?**

Pass the code received so far to the code prop with status set to streaming, then switch status to complete when the response ends. Rows stay in place as lines are added.

**Which languages are highlighted?**

The language prop accepts typescript, tsx, json, bash, diff and text, and defaults to typescript.

**Can I change what copy does?**

Yes. Pass onCopy to replace the default clipboard write, or set copyable to false to hide the button. highlightLines takes line numbers to emphasize.

## React Native

A React Native version ships in beUI Native. The detail JSON has every file to copy.

```bash
npx expo install prism-react-renderer react-native-reanimated react-native-svg react-native-worklets
npm install uniwind tailwindcss
```

- Native detail: https://beui.dev/native/r/code-block
- GitHub: https://github.com/starc007/beui-native/tree/main/src/components/code-block

## Source

- Registry detail: https://beui.dev/r/code-block
- Raw source: https://beui.dev/r/code-block/raw
- GitHub: https://github.com/starc007/ui-components
