CodeBlock
StableA dark box for code, with the language name and a Copy button.
Also known as code snippet, syntax highlighter, pre, code viewer
Install with npm install @tattva/ui (setup), or copy the code from the kit in Downloads.
With a language
function total(items) {
return items.reduce((sum, i) => sum + i.price, 0);
}<CodeBlock language="ts" code={sampleCode} />The language is only a name shown on top.
When to use it
Shows code exactly as written, on a dark panel so it stands apart from the words around it. Long lines scroll sideways instead of wrapping, so nothing is broken up.
Made of: Language name · Copy button · Code area
Do and avoid
{
"invoice": "INV-2041",
"status": "paid"
}statusDo
- Set the language so people know what they are copying.
- Use it for multi-line code and commands in replies.
- Remove blank lines at the end of the code.
Avoid
- Do not use it for a single word in a sentence. Use inline code styling.
- Do not expect long lines to wrap. They scroll sideways.
- Do not paste in secrets like passwords. Anything shown can be copied.
On a phone
- Long lines scroll sideways inside the block and do not wrap, so the page itself does not scroll sideways.
- The Copy button keeps its size and has a 44px tap area on touch screens, so the header row does not get taller.
- If the browser blocks clipboard access, Copy does nothing and shows no error.
Properties
| Prop | Type | Default | Description |
|---|---|---|---|
| coderequired | string | none | Source text shown in the block and copied to the clipboard. |
| language | string | "text" | Label shown in the caption. It does not trigger highlighting. |
"Show code under the preview gives the code for the example on the stage."
States
States this part has beyond its default look. Build each one your screen can reach. States set by a property are in the Code tab.
- copied
- After a successful copy the Copy button shows a check and the word Copied for about 1.5 seconds.
- focus
- The Copy button and the scrollable code area each show a focus ring on keyboard focus.
- scrolling
- A line wider than the block scrolls sideways instead of wrapping.
Tokens
Change one of these and every part that uses it follows.
--code-bg--code-fg--code-muted--border--radius-card
Built in
- The box is a figure, and the bar with the language name is its caption.
- Copy is a real button with visible words. Screen readers politely hear "Copied" when it works.
- The Tab key can reach the code area, so keyboard users can scroll long lines with the arrow keys.
- The icons are hidden from screen readers.
What you need to do
- Explain what the code does in the words around it. The language name alone is not enough.
- Tell people when copying fails. The button stays silent when the clipboard is blocked.
Built toward WCAG 2.2 AA and checked automatically; no independent audit yet. Read the accessibility guide