Skip to content

shadcn.io is an independent project built on shadcn/ui

Components

Free

Code Block for Solid

A Solid code block for Ark UI projects: a title, a copy button, line numbers, diff markers and synchronous highlighting for code and terminal output.

On this page10 sections
UI library: Ark UI

Code Block shows text that has to be read or copied exactly as written: a source file, a shell command, a stack trace, an agent's tool output. A header holds a title and a copy button, and each line can carry a number, a highlight or a diff marker. Highlighting comes from a separate hook, so a block of plain output stays light.

For code people edit before copying, use a Code Editor. For an agent's step with its output folded away, put the block in a Trace.

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

The install also adds the useHighlightedCode hook, the highlighter it runs on and the color variables it reads, for syntax highlighting.

Anatomy

Code Block anatomy: root, header, title, actions, content, line

Usage

import {
  CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton,
  CodeBlockHeader, CodeBlockTitle,
} from "@/components/ui/code-block";

CodeBlockContent takes the text as a string, or one CodeBlockLine per line when a line needs a variant or highlighted tokens. CodeBlockCopyButton copies its value, so this one copies the command without the prompt.

<CodeBlock>
  <CodeBlockHeader>
    <CodeBlockTitle>Terminal</CodeBlockTitle>
    <CodeBlockActions>
      <CodeBlockCopyButton value="pnpm dev" />
    </CodeBlockActions>
  </CodeBlockHeader>
  <CodeBlockContent>$ pnpm dev</CodeBlockContent>
</CodeBlock>

Accessibility

CodeBlockContent is a pre around a code element, set to dir="ltr" so code keeps its order on a right-to-left page. It is in the tab order, so a keyboard can focus it and scroll a long line or a capped block. CodeBlockCopyButton is named Copy, and a polite live region says Copied after a copy, or Couldn't copy when the copy fails. Line numbers carry empty alternative text, so screen readers skip them where the browser supports it.

Left to you: an aria-label on each icon button you add, aria-pressed on a toggle, and a title that names what failed on a destructive block.

Tab
Moves focus through the block in source order: the buttons in the header, then the content, then any buttons in the footer.
Shift+Tab
Moves focus back the same way.
Arrow Down
When the content has focus and is taller than its box, scrolls it down.
Arrow Up
When the content has focus and is taller than its box, scrolls it up.
Arrow Right
When the content has focus and a line runs past its box, scrolls it right.
Arrow Left
When the content has focus and a line runs past its box, scrolls it left.
Enter
When focus is on the copy button, copies its value.
Space
When focus is on the copy button, copies its value.

Demos

Basic

A build log handed to CodeBlockContent as a plain string, with no header and no buttons. The text renders as one text node, which keeps each update cheap while output streams in. Start here for tool output that only needs reading, and add a header once people need a title or a copy button.

Preview width

A Terminal title with an icon, and a copy button at the end of the header that copies only the pnpm add command, not the output under it. CodeBlockCopyButton copies its value, whatever the block shows. A long title truncates instead of pushing the button out, and it still does when you wrap CodeBlockTitle in a link to the file.

Preview width

Actions

Lint output with wrap, download and copy buttons in CodeBlockActions. The block keeps no wrap state of its own, so the demo holds it, starts it on and passes it to wrap, and the toggle reports it with aria-pressed. Add an action when people do something with the text, and give each icon button an aria-label.

Preview width

Floating actions

An install log with no header and a copy button in its top corner. CodeBlockActions placed directly inside CodeBlock floats at the top end, hidden until the block is hovered or holds focus, and always shown on a touch screen. Use it for a short snippet where a header row would be more chrome than code.

Preview width

Line numbers

A package.json numbered in the gutter. With lineNumbers, CodeBlockContent splits its text into lines and counts them with a CSS counter, so the numbers never land in a copied selection. Number a file people will discuss line by line, and leave a one-line command bare.

Preview width

Start line

Eleven lines from the middle of app/dashboard/page.tsx, numbered from 995 to 1005. startLine sets the first number, and the gutter widens to fit four digits. Use it when the numbers should match the file the code came from, as in a stack trace or a review comment.

Preview width

Wrap

The same long model error twice, first scrolling sideways and then wrapped. Lines scroll by default, which keeps the indentation of code intact. Add wrap for prose-like output such as error messages and tool results, where scrolling would hide the end of the sentence, or let people choose with a toggle as in Actions.

Preview width

Highlighted lines

A numbered config object with its two experimental flags tinted. Render each line as a CodeBlockLine and set variant to highlighted on the ones to call out. Point at the few lines the text around the block talks about, because a block where every line is tinted points at nothing.

Preview width

Diff

A change to components/greeting.tsx, with one line removed and three added. Setting variant to removed or added on a CodeBlockLine tints it and puts a − or + in the gutter, outside any text selection. The demo reads each marker off the first character of a patch row, and its copy button copies the patch itself, markers included.

Preview width

Height

Forty request logs in a block capped by max-h-48 on CodeBlockContent, so they scroll inside its border. The scroll-fade utility fades the edges that have more to show: left and right by default, top and bottom once lines wrap. A capped block that doesn't wrap needs scroll-fade-y as well, as this one has.

Preview width

Show more

A 34-line components/chat.tsx cut off at max-h-64, with a Show more button in CodeBlockFooter. The demo holds expanded, drops the cap once it is set, and gives the button aria-expanded and aria-controls pointing at the content's id. Use it for a long file in a chat message, where most people only need the top.

Preview width

Max height

The same 34-line file, but Show more raises the cap to max-h-96 instead of removing it, and the content scrolls inside the block with faded edges. Raise the cap when the whole file could take over the page, such as a long answer in a narrow chat column.

Preview width

Size

The same install output at both sizes. Setting size to sm tightens the padding and sets the code in text-xs, for tool output and Trace steps that sit beside other content. Keep the default size when the code is the point of the page.

Preview width

Destructive

A stack trace for a failed render, titled Error. Setting variant to destructive draws the edge, the title and the text in the destructive color, so a failure reads as one at a glance. Use it for failed output, and still name what failed in the title, since the color says nothing to a screen reader.

Preview width

Trace

Two shell steps in a Trace, one passed and one failed, each with its output in a small block inside TraceCollapsibleContent. Both blocks set size to sm, with wrap and max-h-64 on their content, so long output wraps and scrolls inside the step. The failed step's block is destructive, and both keep their own text color instead of the trace's muted one.

Preview width

Tabs

Three files of one change in Tabs, with a CodeBlock in each TabsContent. The tab shows the file name and the block's title its full path. Use tabs when people read the files one at a time, and stack the blocks when they need to compare two.

Preview width

Message

A question and its answer, with a route handler between two paragraphs of a Message. The block takes the column's width and keeps its own border, so it reads as part of the answer. Keep the sentence that explains the code beside the block, not in a comment inside it.

Preview width

Typeset

A heading, two paragraphs and a numbered block inside a Prose article, where the block keeps its own styles and gets the same space above as a paragraph. The rules the Prose install adds skip the code inside the block, so it needs no class to opt out. Use it for docs pages and long answers, where the code is one part of the text.

Preview width

RTL

A sentence and a terminal block in Arabic, with a select to switch to Hebrew or English. The header follows the direction set on its parent, so the title sits at the start and the copy button at the end, while the commands and their line numbers keep reading left to right. Set dir on the page or a parent, and the block follows it.

Preview width

Syntax highlighting

A weather tool's JSON result, colored. useHighlightedCode(code, language) returns one rendered line per line of code, and each goes inside a CodeBlockLine. Every token is a span with a class on a CSS variable, such as text-(--th-string), so the colors come from your theme, not from inline styles.

Preview width

Languages

A CSS file, a Python function and a plain-text note, each passed through its own call to the hook. text isn't a language the highlighter lists, so the note comes back as plain lines with no error. The FAQ lists the 13 languages and how to add another.

Preview width

Terminal output

A test run with green passes, a red failure and dim test counts. Passing "ansi" as the language turns escape codes into classes: the 16 terminal colors as text or background, 256-color and RGB codes mapped to the nearest of those, plus bold, dim, italic, underline, strikethrough and inverse. Colors don't carry over to the next line, and the copy button copies the text through stripAnsi.

Preview width

Streaming

Press Replay to watch five blocks written three characters at a time: a hook, an install command, a diff, a route with highlighted lines and an env file. Each copy button stays disabled until its block is complete. The hook tokenizes the code again on every update, and a line that didn't change keeps the nodes it already had, so it isn't rendered again.

Preview width

Server rendering

useHighlightedCode is synchronous, so a page that calls it is already colored in the HTML SolidStart renders on the server, with nothing to load or await. The hook and lib/highlighter-core.ts under it are the whole highlighter on Solid. There is no async highlightCode here, because nothing has to wait.

FAQ

How do I add syntax highlighting to a Code Block in Solid?

Call useHighlightedCode(code, language) and map over the accessor it returns, putting each line inside a CodeBlockLine in CodeBlockContent, as the Syntax highlighting demo does. Pass an accessor as code when the text changes.

Highlighting is synchronous, so the first render is already colored and there is nothing to load. A language the highlighter doesn't list comes back as plain lines, with no error.

Which languages does Code Block highlight, and how do I add one?

Thirteen: bash, css, diff, html, javascript, json, jsx, markdown, python, sql, tsx, typescript and yaml. The aliases js, ts, md, py, sh, shell, shellscript, zsh and yml work too, and "ansi" colors terminal output.

To add one, import its grammar from @tanstack/highlight/languages/<name> in lib/highlighter-core.ts and add it to the languages object there. TanStack Highlight 1.1 ships 25 more, among them Go, Rust, Swift, PHP, TOML, Vue and Svelte. Only the grammars that file imports end up in your bundle.

How do I change the Code Block's syntax highlighting colors?

Set the --th-* variables in your theme. Each token is a span with a class on one of them, such as text-(--th-keyword), never an inline style. The install adds 20 token variables, --th-keyword, --th-string, --th-comment and the rest, plus 16 terminal colors from --th-ansi-black to --th-ansi-bright-white, with GitHub's light and dark palettes as their values.

Change them under :root and .dark, or point them at your own tokens, such as --th-keyword: var(--primary), and every block in your app follows.

Can a Code Block show code while an AI response is still streaming?

It is built for that. A string passed to CodeBlockContent renders as one text node, so each new chunk only changes that node. With highlighting, the hook tokenizes the whole code again on each update and keeps what it rendered for every line whose content didn't change, so only new and changed lines render again.

Pass the streamed text as an accessor, so the lines follow it.

Set disabled on the copy button until the block is complete, as the Streaming demo does.

What does the Code Block copy button copy?

Its value prop and nothing else, since the button never reads what the block shows. A header can copy only the command while the block shows the command and its output, as the Header demo does. For terminal output, pass the text through stripAnsi from lib/highlighter-core.ts, so the escape codes stay out of the clipboard.

A selection made by hand is a different matter. Line numbers and diff markers are drawn by CSS, so they never land in it, and an empty line keeps its newline.

Why does the Code Block copy button show a cross instead of copying?

The browser either offered no clipboard or refused the write. The button writes with navigator.clipboard.writeText, which browsers only provide on a secure origin: HTTPS or localhost. On a page served over plain HTTP, such as a dev server opened from a phone at its network address, there is no clipboard at all.

A secure page can still refuse, for example in an iframe that isn't allowed to use the clipboard. Either way the button shows a cross for two seconds and sets data-failed for your own styles, while its live region says Couldn't copy. Try the button on the origin you deploy to before you count on it.

How do I show a diff or highlight lines in a Code Block?

Render each line as a CodeBlockLine and set its variant. added and removed tint the line and put a + or − in the gutter, outside any text selection, while highlighted tints it with no marker. The Diff demo reads the variant off the first character of each patch row and drops that character from the line.

The variants work alongside lineNumbers and highlighted tokens, as the diff in the Streaming demo shows. In eight of the nine styles, an added line has the same tint as a highlighted one and only the + tells them apart, so keep the two out of the same block.

How do I change a Code Block's padding, font size or border?

Edit the code block file in components/ui, which is your code once installed. Each part sets its own classes, and the parts read the root's data-size and data-variant through Tailwind group variants, which is how size set to sm reaches the header, the content and every line.

Every part also has a data-slot, such as code-block-header or code-block-line, to target from your own CSS. For height, a max-h-* class on CodeBlockContent caps the block and lets it scroll, as the Height demo does.

API Reference

CodeBlock

<div> data-slot="code-block"

PropType
size?"default" | "sm"

sm has tighter padding and text-xs code, for tool and trace output.

Type
"default" | "sm"
Default
"default"
variant?"default" | "destructive"

The tone: destructive for errors and failed output.

Type
"default" | "destructive"
Default
"default"
class?string

Merged with the part's classes.

AttributeType
data-size?string

Mirrors size.

data-variant?string

Mirrors variant.

CodeBlockActions

<div> data-slot="code-block-actions"

PropType
class?string

Merged with the part's classes.

CodeBlockContent

<pre> data-slot="code-block-content"

PropType
lineNumbers?boolean

Number each line. children is split into lines when it is a string; * anything else needs one CodeBlockLine per line.

Default
false
startLine?number

The number of the first line, when lineNumbers is set.

Default
1
wrap?boolean

Wrap long lines instead of scrolling.

Default
false
class?string

Merged with the part's classes.

AttributeType
data-numbered?string

Present when lineNumbers is set.

data-wrap?string

Present when wrap is set.

CodeBlockCopyButton

data-slot="code-block-copy-button"

PropType
valuestring

The text it copies, whatever the block shows.

clickEffect?boolean

Apply a click effect to the button.

Default
true
isLoading?boolean

Show a loading indicator.

Default
false
pill?boolean

Fully rounded corners.

Default
false
size?"default" | "icon" | "icon-lg" | "icon-md" | "icon-sm" | "icon-xl" | "icon-xs" | "lg" | "md" | "sm" | "xl" | "xs"

Ark default: md.

Type
"default" | "icon" | "icon-lg" | "icon-md" | "icon-sm" | "icon-xl" | "icon-xs" | "lg" | "md" | "sm" | "xl" | "xs"
Default
"icon-xs"
variant?"default" | "destructive" | "ghost" | "link" | "outline" | "secondary"

Ark default: default.

Type
"default" | "destructive" | "ghost" | "link" | "outline" | "secondary"
Default
"ghost"
asChild?(props: ParentProps) => JSX.Element

Render your own element: a function that gets the part's props to spread on it.

Type
(props: ParentProps) => JSX.Element
class?string

Merged with the part's classes.

AttributeType
data-copied?string
data-failed?string

CodeBlockFooter

<div> data-slot="code-block-footer"

PropType
class?string

Merged with the part's classes.

CodeBlockHeader

<div> data-slot="code-block-header"

PropType
class?string

Merged with the part's classes.

CodeBlockLine

<span> data-slot="code-block-line"

PropType
variant?"added" | "default" | "highlighted" | "removed"

The line's state: added and removed tint it and add a + or − marker, highlighted tints it.

Type
"added" | "default" | "highlighted" | "removed"
Default
"default"
class?string

Merged with the part's classes.

AttributeType
data-variant?string

Mirrors variant.

CodeBlockTitle

<div> data-slot="code-block-title"

PropType
class?string

Merged with the part's classes.

useHighlightedCode

const lines = useHighlightedCode(code, language);

Returns one rendered line per line of code, to put inside CodeBlockLine. A language that isn't in the list comes back as plain lines.

The lines are node lists, in an accessor, and code and language may each be an accessor.

ArgumentTypeDescription
codestringThe code to highlight. A trailing newline is ignored.
languagestringA language or alias from lib/highlighter-core.ts, or "ansi".