Code Block
Code panel with tabs, line numbers, highlighted lines and a copy button.
- 2.9 KB gzipped
- Deps: lucide-react
- Reduced-motion safe
- Base UI & Radix compatible
counter.tsxtsx
import { useState } from "react"; // A counter that remembers its last valueexport function Counter({ start = 0 }: { start?: number }) { const [count, setCount] = useState(start); const label = `Clicked ${count} times`; return ( <button type="button" onClick={() => setCount(count + 1)}> {label} </button> );}Installation
pnpm dlx shadcn@latest add https://velora.colorlib.com/r/code-block.jsonAdds components/velora/code-block.tsx, installs lucide-react.
Examples
File tabs
A component and its usage as two file tabs, each with its own highlighted lines.
tsx
import { cn } from "@/lib/utils"; interface BadgeProps extends React.HTMLAttributes<HTMLSpanElement> { tone?: "neutral" | "success";} export function Badge({ tone = "neutral", className, ...props }: BadgeProps) { return ( <span className={cn( "rounded-full px-2.5 py-0.5 text-xs font-medium", tone === "success" && "bg-emerald-500/15 text-emerald-700", className )} {...props} /> );}Props
| Prop | Type | Default |
|---|---|---|
codeSource to show (ignored when `tabs` is set) | string | "" |
languageLanguage for highlighting: tsx, ts, jsx, js, css, bash, json | string | "tsx" |
filenameFile name shown in the header and used as the code region's label | string | — |
tabsSeveral files, shown as tabs | CodeFile[] | — |
highlightLines1-based line numbers to highlight | number[] | [] |
lineNumbersShow the line-number gutter | boolean | true |
Also accepts every <div> attribute, forwarded to the root element.
CodeFile
interface CodeFile {
name: string;
code: string;
language?: string;
highlightLines?: number[];
}Accessibility
- Reduced motion
- Nothing animates, so there is no reduced-motion difference; the copy icon swaps to a check mark instantly.
- Keyboard
- The code area is focusable and scrolls with the arrow keys. With tabs, the tab list is one Tab stop: Left/Right arrows, Home and End switch files. The copy button is a native button.
- Screen readers
- The code region is labelled with the file name, line numbers are aria-hidden, tabs use tablist/tab/tabpanel roles, and a status region announces "Copied to clipboard".