Code Block

Code with syntax colors in SF Mono, a title, line numbers and a copy button.

@cupertinoui/code-blockRegistry JSON

Installation

pnpm dlx shadcn@latest add @cupertinoui/code-block

The first install also adds the macOS theme. See Installation to set up the registry.

Usage

import { CodeBlock, CodeBlockContent, CodeBlockLine } from "@/components/ui/code-block"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"

const lines = useHighlightedCode(code, "tsx")

<CodeBlock>
  <CodeBlockContent>
    {lines.map((line, i) => <CodeBlockLine key={i}>{line}</CodeBlockLine>)}
  </CodeBlockContent>
</CodeBlock>
useHighlightedCode colors code with Shiki in the browser, loading each language the first time it is used, and keeps up with code that streams in.

API Reference

Every part forwards the props of the underlying element. The props below are the ones CupertinoUI adds or changes.

CodeBlockContent

PropTypeDescription
lineNumbersboolean
Default: false
Numbers the lines.
wrapboolean
Default: false
Wraps long lines.
classNamestringExtra classes, merged with the component's own.

CodeBlockLine

PropTypeDescription
variant"default" | "added" | "removed" | "highlighted"
Default: "default"
Marks a line, e.g. in a diff.
classNamestringExtra classes, merged with the component's own.

CodeBlockCopyButton

PropTypeDescription
valuestringThe text to copy.
classNamestringExtra classes, merged with the component's own.