- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Attachment
- Avatar
- Badge
- Breadcrumb
- Bubble
- Button
- Button Group
- Calendar
- Card
- Carousel
- Chart
- Checkbox
- Code Block
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Direction
- Drawer
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Kbd
- Label
- Marker
- Menubar
- Message
- Message Scroller
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Questionnaire
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toast
- Toggle
- Toggle Group
- Tooltip
- Trace
- Typography
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", system: "You are a helpful assistant. Answer in one short paragraph.", messages, })
return result.toUIMessageStreamResponse()}"use client"
import * as React from "react"CodeBlock displays code, terminal output, logs and diffs. It has a header with a title and actions, line numbers, wrapping, diff and highlighted lines, and a small size for tool output in a Trace.
Syntax highlighting is optional and lives in a separate hook, so a block that only shows plain output stays small.
Installation#
pnpm dlx shadcn@latest add code-block
code-block also installs useHighlightedCode for syntax highlighting.
Usage#
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
} from "@/components/ui/code-block"<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Terminal</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>Composition#
CodeBlock
├── CodeBlockHeader
│ ├── CodeBlockTitle
│ └── CodeBlockActions
│ └── CodeBlockCopyButton
├── CodeBlockActions (floating, when there is no header)
├── CodeBlockContent
│ └── CodeBlockLine
└── CodeBlockFooterCodeBlockContent takes a string or a list of CodeBlockLine. Use lines when you need line variants or highlighted tokens.
Features#
- It streams cheaply. A string child renders as one text node, and the highlighter tokenizes only the new lines as code arrives.
- It copies cleanly. Line numbers and diff markers are left out of a selection, and blank lines survive the copy.
- It reads left to right. The content is always
dir="ltr". The header follows the page direction. - It highlights without WASM.
useHighlightedCodeuses Shiki's JavaScript engine, loads each language on first use and renders ANSI colors in terminal output. On the server,highlightCodekeeps Shiki out of the client bundle. - It fits where code shows up. Use it in a message, a Markdown fence, a Trace line, Tabs, a Dialog or a
typesetcontainer. - It scrolls by keyboard. The content is focusable, and floating actions show on focus as well as on hover.
Basic#
Pass a string to CodeBlockContent. It renders as one text node, so it stays cheap while output streams.
$ pnpm build
> next build
✓ Compiled successfully in 4.2s
✓ Generating static pages (12/12)
Route (app) Size First Load JS
┌ ○ / 1.9 kB 112 kB
├ ○ /_not-found 993 B 103 kB
└ ƒ /api/chat 141 B 102 kBimport { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output = `$ pnpm buildHeader#
CodeBlockHeader holds a CodeBlockTitle and CodeBlockActions. CodeBlockCopyButton copies its value.
$ pnpm add ai @ai-sdk/react zod
Packages: +14
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0import { TerminalIcon } from "lucide-react"
import {A long title truncates. To link the title to a file, wrap CodeBlockTitle in an anchor.
<CodeBlockHeader>
<a href="/files/route.ts">
<CodeBlockTitle>app/api/chat/route.ts</CodeBlockTitle>
</a>
</CodeBlockHeader>Actions#
CodeBlockActions holds any number of buttons. For a wrap toggle, keep the state yourself and pass it to wrap.
$ pnpm lint
apps/web/components/message-list.tsx
18:22 error 'messages' is possibly 'undefined'. Add a guard before calling map @typescript-eslint/no-unsafe-call
42:7 warning React Hook React.useEffect has a missing dependency: 'scrollToBottom' react-hooks/exhaustive-deps
✖ 2 problems (1 error, 1 warning)"use client"
import * as React from "react"const [wrap, setWrap] = React.useState(false)
<CodeBlockActions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap}
onClick={() => setWrap(!wrap)}
>
<WrapTextIcon />
</Button>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
<CodeBlockContent wrap={wrap}>{output}</CodeBlockContent>Floating Actions#
Without a header, put CodeBlockActions directly inside CodeBlock. The actions float at the top end and stay hidden until the block is hovered or focused. They always show on touch screens.
$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
dependencies:
+ @ai-sdk/react 3.0.12
+ ai 6.0.12
+ zod 4.1.12
Done in 2.8s using pnpm v10.18.0import {
CodeBlock,
CodeBlockActions,Line Numbers#
Add lineNumbers to CodeBlockContent. A string child is split into lines, and the numbers are not copied with a selection.
{ "name": "chat", "private": true, "scripts": { "dev": "next dev", "build": "next build" }}import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const code = `{Start Line#
Set startLine to number lines from a given line, for a snippet from the middle of a file. The gutter grows to fit the widest number.
if (!session) { redirect("/login") }
const projects = await db.project.findMany({ where: { ownerId: session.user.id }, orderBy: { updatedAt: "desc" }, })
return <ProjectList projects={projects} />}"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"Wrap#
Long lines scroll by default. Add wrap to wrap them, which suits tool output and error messages. To let the reader toggle it, see Actions.
Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output = `Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.`Highlighted Lines#
Render each line as a CodeBlockLine and set variant="highlighted" on the lines to call out.
export default { experimental: { reactCompiler: true, viewTransition: true, }, images: { remotePatterns: [{ hostname: "avatars.githubusercontent.com" }], },}import {
CodeBlock,
CodeBlockContent,Diff#
Set variant="added" or variant="removed" on a CodeBlockLine. Each one adds a + or − marker.
export function Greeting({ name }: { name: string }) { return <p>Hello, {name}</p> return <p className="text-sm text-muted-foreground"> Hello, {name}! </p>}import {
CodeBlock,
CodeBlockActions,Height#
Cap the height with a max-h-* class on CodeBlockContent. The content scrolls inside the block.
[01] GET /api/chat 200 in 12ms
[02] GET /api/chat 200 in 19ms
[03] GET /api/chat 200 in 26ms
[04] GET /api/chat 200 in 33ms
[05] GET /api/chat 200 in 40ms
[06] GET /api/chat 200 in 47ms
[07] GET /api/chat 200 in 14ms
[08] GET /api/chat 200 in 21ms
[09] GET /api/chat 200 in 28ms
[10] GET /api/chat 200 in 35ms
[11] GET /api/chat 200 in 42ms
[12] GET /api/chat 200 in 49ms
[13] GET /api/chat 200 in 16ms
[14] GET /api/chat 200 in 23ms
[15] GET /api/chat 200 in 30ms
[16] GET /api/chat 200 in 37ms
[17] GET /api/chat 200 in 44ms
[18] GET /api/chat 200 in 51ms
[19] GET /api/chat 200 in 18ms
[20] GET /api/chat 200 in 25ms
[21] GET /api/chat 200 in 32ms
[22] GET /api/chat 200 in 39ms
[23] GET /api/chat 200 in 46ms
[24] GET /api/chat 200 in 13ms
[25] GET /api/chat 200 in 20ms
[26] GET /api/chat 200 in 27ms
[27] GET /api/chat 200 in 34ms
[28] GET /api/chat 200 in 41ms
[29] GET /api/chat 200 in 48ms
[30] GET /api/chat 200 in 15ms
[31] GET /api/chat 200 in 22ms
[32] GET /api/chat 200 in 29ms
[33] GET /api/chat 200 in 36ms
[34] GET /api/chat 200 in 43ms
[35] GET /api/chat 200 in 50ms
[36] GET /api/chat 200 in 17ms
[37] GET /api/chat 200 in 24ms
[38] GET /api/chat 200 in 31ms
[39] GET /api/chat 200 in 38ms
[40] GET /api/chat 200 in 45msimport {
CodeBlock,
CodeBlockActions,CodeBlockContent fades its edges with scroll-fade as it scrolls: left and right by default, top and bottom when it wraps. Add scroll-fade-y to a capped block that does not wrap.
Show More#
CodeBlockFooter is a slot below the content. For Show More, cap the content while it is collapsed and put a ghost xs Button in the footer.
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"
export function Chat() { const [input, setInput] = React.useState("") const { messages, sendMessage, status } = useChat()
return ( <div className="flex flex-col gap-4"> {messages.map((message) => ( <div key={message.id}> {message.parts.map((part, index) => part.type === "text" ? <p key={index}>{part.text}</p> : null )} </div> ))} <form onSubmit={(event) => { event.preventDefault() sendMessage({ text: input }) setInput("") }} > <Input value={input} onChange={(event) => setInput(event.target.value)} /> <Button disabled={status !== "ready"}>Send</Button> </form> </div> )}"use client"
import * as React from "react"const [expanded, setExpanded] = React.useState(false)
const id = React.useId()
<CodeBlockContent
id={id}
className={expanded ? undefined : "max-h-64 overflow-y-hidden scroll-fade-y"}
>
{code}
</CodeBlockContent>
<CodeBlockFooter className="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded(!expanded)}
>
{expanded ? "Show less" : "Show more"}
</Button>
</CodeBlockFooter>Max Height#
To keep a long block from taking over the page, raise the cap instead of removing it. The expanded content scrolls, and the edges fade as you scroll.
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"
export function Chat() { const [input, setInput] = React.useState("") const { messages, sendMessage, status } = useChat()
return ( <div className="flex flex-col gap-4"> {messages.map((message) => ( <div key={message.id}> {message.parts.map((part, index) => part.type === "text" ? <p key={index}>{part.text}</p> : null )} </div> ))} <form onSubmit={(event) => { event.preventDefault() sendMessage({ text: input }) setInput("") }} > <Input value={input} onChange={(event) => setInput(event.target.value)} /> <Button disabled={status !== "ready"}>Send</Button> </form> </div> )}"use client"
import * as React from "react"Size#
Use size="sm" for tool and Trace output. It has tighter padding and text-xs text.
$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0import { TerminalIcon } from "lucide-react"
import {Destructive#
Use variant="destructive" for errors and failed output.
TypeError: Cannot read properties of undefined (reading 'map')
at MessageList (components/message-list.tsx:18:22)
at renderWithHooks (react-dom.development.js:16305:18)import {
CodeBlock,
CodeBlockActions,Trace#
Put a CodeBlock with size="sm" in TraceCollapsibleContent for tool and terminal output. Add wrap and a max-h-64 class to CodeBlockContent so long output wraps and scrolls inside the trace. The block sets its own text color, so TraceCollapsibleContent does not mute it.
$ node --version
v24.18.0$ pnpm dev
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1908:16)import { TerminalIcon } from "lucide-react"
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"Tabs#
Show several files with Tabs, one CodeBlock in each TabsContent.
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json() const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()}"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"Message#
Put a CodeBlock between paragraphs inside a Message.
Create a route handler that returns the stream:
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages, })
return result.toUIMessageStreamResponse()}The client reads it with useChat.
"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"Typeset#
A CodeBlock inside a typeset container keeps its own styles and gets the same space above as a paragraph.
Stream a response
Create a route handler that calls streamText and returns the stream to the client.
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json() const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()}The useChat hook reads the stream on the client and renders the answer while it is written.
"use client"
import { FileCodeIcon } from "lucide-react"RTL#
To enable RTL support in shadcn/ui, see the RTL configuration guide. Code always reads left to right. The header follows the page direction.
ثبّت الحزم، ثم شغّل خادم التطوير.
pnpm add ai @ai-sdk/react zodpnpm dev"use client"
import { TerminalIcon } from "lucide-react"Syntax Highlighting#
useHighlightedCode highlights with Shiki and returns one React node per line for CodeBlockLine.
{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}"use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"const lines = useHighlightedCode(code, "json")
<CodeBlock>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>Shiki uses its JavaScript regex engine, so there is no WASM to load.
Languages#
Each language loads the first time it is used. Edit the list in lib/highlighter.tsx. A language that is not in the list renders as plain text.
@import "tailwindcss";
:root { --radius: 0.625rem;}def greet(name: str) -> str: return f"Hello, {name}!"A language that is not in the list renders as plain text."use client"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"The list ships with bash, css, diff, html, javascript, json, jsx, markdown, python, sql, tsx, typescript and yaml, plus aliases such as ts, js, sh and yml.
Terminal Output#
Pass "ansi" as the language to render the colors in terminal output. Without it, escape codes show as text.
$ pnpm test[32m✓[39m src/format.test.ts [2m(4 tests)[22m[32m✓[39m src/parse.test.ts [2m(7 tests)[22m[31m✗[39m src/stream.test.ts [2m(3 tests | 1 failed)[22m
[31mAssertionError: expected 'hello' to be 'hello world'[39m
Tests [31m1 failed[39m | [32m13 passed[39m (14)"use client"
import { TerminalIcon } from "lucide-react"ANSI colors do not carry from one line to the next.
Server Rendering#
highlightCode is async and works in a Server Component, so Shiki stays out of the client bundle.
import { highlightCode } from "@/lib/highlighter"
export async function ServerCode({ code }: { code: string }) {
const lines = (await highlightCode(code, "tsx")) ?? code.split("\n")
return (
<CodeBlock>
<CodeBlockContent lineNumbers>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
)
}Streaming#
While the code streams, the hook tokenizes only the new lines, starting where the last line left off. Lines that did not change keep the same nodes, so React skips them.
export function useDebounce<T>(value: T, delay = 300) { const [debounced, setDebounced] = React.useState(value)
React.useEffect(() => { const timeout = setTimeout(() => setDebounced(value), delay) return () => clearTimeout(timeout) }, [value, delay])
return debounced}pnpm dlx shadcn@latest add code-blockexport function Search() { const [query, setQuery] = React.useState("") const results = useSearch(query) const debounced = useDebounce(query, 300) const results = useSearch(debounced)
return <SearchResults results={results} />}import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages, })
return result.toUIMessageStreamResponse()}AI_GATEWAY_API_KEY=your-api-key"use client"
import * as React from "react"Markdown#
Render the message with Streamdown and route fenced code to a CodeBlock with components.code. Streamdown sets data-block on fenced code only, so inline code stays inline.
Wrap the value in a useDebounce hook. It returns the latest value once it stops changing for delay milliseconds.
export function useDebounce<T>(value: T, delay = 300) { const [debounced, setDebounced] = React.useState(value)
React.useEffect(() => { const timeout = setTimeout(() => setDebounced(value), delay) return () => clearTimeout(timeout) }, [value, delay])
return debounced}Pass the debounced value to your fetch instead of the raw input.
"use client"
import * as React from "react"useIsCodeFenceIncomplete returns true until the closing fence arrives. Use it to disable the copy button while the code is incomplete. It only works when Streamdown gets isAnimating, so pass isAnimating while the message streams.
<Streamdown components={{ code: MarkdownCode }} isAnimating={isStreaming}>
{text}
</Streamdown>Accessibility#
CodeBlockContentis aprewith acodeelement and always setsdir="ltr", so code reads left to right on an RTL page.CodeBlockContenthastabIndex={0}, so keyboard users can focus it and scroll it. PasstabIndex={-1}to remove the tab stop.- Floating actions show when focus is inside the block, not only on hover, so keyboard users can reach them.
- Line numbers are hidden from screen readers.
- Diff lines carry a
+or−marker as well as a tint, so the change does not rely on color. CodeBlockCopyButtonis labelled "Copy", and a polite live region announces "Copied" after a successful copy.- Give a wrap toggle
aria-pressedso its state is announced. - Give a Show More button
aria-expandedand pointaria-controlsat theidofCodeBlockContent.
API Reference#
CodeBlock#
The surface that holds the header, the content and the footer.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "default" | "destructive" | "default" | The tone of the block. |
size | "default" | "sm" | "default" | "sm" has tighter padding and text-xs code, for tool output. |
className | string | - | Additional classes to apply to the block. |
CodeBlockHeader#
A row above the content for a title and actions.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the header. |
CodeBlockTitle#
A filename or a label, with an optional icon. It truncates.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the title. |
CodeBlockActions#
Holds buttons at the end of the header. As a direct child of CodeBlock, it floats.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the actions. |
CodeBlockCopyButton#
A ghost icon button that copies value to the clipboard. It accepts the props of Button.
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | - | Required. The text to copy. |
className | string | - | Additional classes to apply to the button. |
CodeBlockContent#
The pre that scrolls or wraps.
| Prop | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | - | A string, or a list of CodeBlockLine. |
wrap | boolean | false | Wrap long lines instead of scrolling. |
lineNumbers | boolean | false | Number each line. A string child is split into lines. |
startLine | number | 1 | The number of the first line, when lineNumbers is set. |
tabIndex | number | 0 | Makes the content focusable so it can be scrolled by keyboard. |
className | string | - | Additional classes to apply to the content, such as max-h-72. |
CodeBlockLine#
One line of code.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "default" | "added" | "removed" | "highlighted" | "default" | The state of the line. |
className | string | - | Additional classes to apply to the line. |
CodeBlockFooter#
A row below the content, such as for a Show More button.
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional classes to apply to the footer. |
useHighlightedCode#
const lines = useHighlightedCode(code, language)Returns one React node per line. It returns plain lines until the first pass finishes, and for a language that is not in the list.
| Argument | Type | Description |
|---|---|---|
code | string | The code to highlight. A trailing newline is ignored. |
language | string | A language or alias from lib/highlighter.tsx, or "ansi". |
On This Page
InstallationUsageCompositionFeaturesBasicHeaderActionsFloating ActionsLine NumbersStart LineWrapHighlighted LinesDiffHeightShow MoreMax HeightSizeDestructiveTraceTabsMessageTypesetRTLSyntax HighlightingLanguagesTerminal OutputServer RenderingStreamingMarkdownAccessibilityAPI ReferenceCodeBlockCodeBlockHeaderCodeBlockTitleCodeBlockActionsCodeBlockCopyButtonCodeBlockContentCodeBlockLineCodeBlockFooteruseHighlightedCode