Code Block
A code block with a copy button, optional line numbers and a fold for long snippets. No highlighter attached.
Installation
Copy and paste the following code into your project.
Update the import paths to match your project structure.
Anatomy
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 |
failedLabel | string | 'Copy failed' | Announced when the clipboard write fails |
onCopied | (code: string) => void | - | Called after the clipboard write |
className | string | - | Additional CSS classes |
CodeBlock.Content
The code is a focusable region, so keyboard users can scroll long lines sideways.
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | '{language} code' | Accessible name of the scrolling region |
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.