Code Block
A code block with a copy button, optional line numbers and a fold for long snippets. No highlighter attached.
import { CodeBlock } from '@/components/ui/code-block';
export function Snippet() {
return (
<CodeBlock code={source} language="tsx">
<CodeBlock.CopyButton />
<CodeBlock.Content />
</CodeBlock>
);
}
Installation
pnpm dlx nachui add code-blockAnatomy
The code goes in as a string on the root, and every part reads it from there. There is no header: the copy button floats in the top right corner and shows on hover, so the block is just the code.
Composition
Use the following composition to build a
CodeBlock:Folding long code
Set
collapsible and the content stops at maxLines. CodeBlock.Expand renders the toggle, and only when there is something to reveal.export const steps = [
{ id: 1, label: 'Step 1', done: true },
{ id: 2, label: 'Step 2', done: true },
{ id: 3, label: 'Step 3', done: true },
{ id: 4, label: 'Step 4', done: true },
{ id: 5, label: 'Step 5', done: true },
{ id: 6, label: 'Step 6', done: true },
{ id: 7, label: 'Step 7', done: true },
Syntax highlighting
There is none built in, on purpose: a highlighter is the one dependency that would double the size of this file. Pass
renderLine and return whatever your highlighter gives you for each line, Shiki tokens included.API Reference
CodeBlock
| Prop | Type | Default | Description |
|---|---|---|---|
code | string | - | The source to display and copy |
language | string | - | Set on data-language and as language-* on the code |
showLineNumbers | boolean | false | Adds a gutter with line numbers |
collapsible | boolean | false | Stops the content at maxLines until expanded |
maxLines | number | 20 | Lines shown while collapsed |
renderLine | (line: string, index: number) => ReactNode | - | Renders each line, for plugging in a highlighter |
className | string | - | Additional CSS classes |
CodeBlock.CopyButton
| Prop | Type | Default | Description |
|---|---|---|---|
copyLabel | string | 'Copy code' | Accessible name at rest |
copiedLabel | string | 'Copied' | Accessible name for 1.5s after copying |
onCopied | (code: string) => void | - | Called after the clipboard write |
className | string | - | Additional CSS classes |
CodeBlock.Content
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
CodeBlock.Expand
| Prop | Type | Default | Description |
|---|---|---|---|
expandLabel | (hidden: number) => string | Show {n} more lines | Label while collapsed |
collapseLabel | string | 'Show less' | Label while expanded |
className | string | - | Additional CSS classes |
Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.