Skip to content

React Code Block With Copy Button

A glass React code block with a small built-in syntax highlighter, line numbers, highlighted and diff lines, a file tab and a copy button.

npx shadcn@latest add https://lokendra-builds.github.io/sheenui/r/code-block.json
total.ts
function total(items: Item[]) {
  return items.reduce((sum, i) => sum + i.price, 0);
}
  • CodeBlock
  • CodeBlockTabs
  • parseLineSpec
  • defaultCodeBlockLabels
  • +2 more

A file with highlighted lines

highlightLines takes "10-11, 16" or an array. Highlighted lines are <mark>; numbers are left out of copy and of screen readers.

components/counter.tsx
import { useState } from "react";
import { Button, GlassCard } from "@sheenui/theme";

type CounterProps = { start?: number; step?: number };

const clamp = <T extends number>(v: T, max: T) => Math.min(v, max); // local: the sample stays self-contained

/** A glass counter: the number springs on every click. */
export function Counter({ start = 0, step = 1 }: CounterProps) {
  const [count, setCount] = useState<number>(start);
  const label = `Clicked ${count} times`;

  return (
    <GlassCard className="flex items-center gap-4 p-6">
      <span aria-live="polite">{label}</span>
      <Button onClick={() => setCount((c) => c + step)}>Add {step}</Button>
    </GlassCard>
  );
}

Files to copy

8 folders · 13 files · 4 packages
From theme/src/
  • components/code-block/
  • components/button/
  • components/spinner/
  • components/status-icons/
  • hooks/{use-controllable.ts, use-direction.ts, use-latest.ts, use-magnetic.ts, use-media-query.ts, use-preferences.ts}
  • motion/{gate.ts, presets.ts, tokens.ts}
  • lib/{cn.ts, form.ts, state-light.tsx, warn-once.ts}
  • styles/
shadcn CLI
npx shadcn@latest add https://lokendra-builds.github.io/sheenui/r/code-block.jsonRegistry item: code-block. The styles need the Tailwind v4 glass UI setup.
The examples also use
  • components/glass-card/
  • motion/light-follower.ts
  • lib/heading.ts
npx shadcn@latest add https://lokendra-builds.github.io/sheenui/r/glass-card.json
Packages
pnpm add @base-ui/react clsx motion tailwind-merge

Diff

addedLines and removedLines render as <ins> / <del> with + and − markers, so color is never the only signal.

motion/tokens.ts
export const spring = {
  snappy: { type: "spring", duration: 0.35, bounce: 0.15 },
  gentle: { type: "spring", duration: 0.5, bounce: 0.2 },
  bouncy: { type: "spring", duration: 0.5, bounce: 0.25 },
  bouncy: { type: "spring", duration: 0.5, bounce: 0.4 },
} as const;

Tabs: commands and languages

CodeBlockTabs keeps several snippets in one block. The underline slides between tabs (transform only); copy and wrap act on the active one. When the tabs don't fit, the hidden edge fades and the list scrolls sideways.

pnpm add motion @base-ui/react
/* Glass that keeps its blur: animate the glass itself. */
.toast {
  --lift: -4px;
  background: var(--sheen-glass-2-bg);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 1.25rem;
  &:hover { translate: 0 var(--lift); }
}

@media (prefers-reduced-motion: reduce) {
  .toast:hover { translate: none !important; }
}

Long lines and no header

Unwrapped, a long line scrolls inside the block (it becomes keyboard-focusable only when it actually scrolls): the line numbers stay pinned and a fade at the end edge shows there is more. Toggle wrap in the header, or start wrapped with defaultWrap. Without a header, copy floats in the corner.

hero.tsx
<Button size="lg" className="motion-ok:hover:-translate-y-0.5 shadow-[0_8px_24px_-10px_var(--sheen-shadow-far)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sheen-focus" onClick={() => track("hero_cta", { variant: "primary", placement: "above-the-fold" })}>Get started</Button>
npx shadcn@latest add https://lokendra-builds.github.io/sheenui/r/carousel.json

CodeBlock

PropTypeDefaultDescription
onCopy(ClipboardEventHandler<HTMLDivElement> & ((code: string) => void))NoneCalled after a successful copy, with the copied text.
showLineNumbersbooleantrue when there is more than one lineShow line numbers.
startLineNumbernumber1Number of the first line (for excerpts of a longer file).
highlightLinesLineSpecNoneLines to highlight: [3, 4] or "3-4, 9". Rendered as <mark>.
addedLinesLineSpecNoneMarks added lines in a diff (green, "+", <ins>).
removedLinesLineSpecNoneMarks removed lines in a diff (red, "−", <del>).
wrapbooleanNoneControlled wrapping of long lines.
defaultWrapbooleanfalseSets the starting wrap state when uncontrolled.
onWrapChange((wrap: boolean) => void)NoneCalled with the new value when the wrap toggle is pressed.
showWrapTogglebooleantrueShow the wrap toggle in the header.
copyablebooleantrueShow the copy button.
maxHeightstring | number"32rem"Taller code scrolls inside. A number is px; "none" never limits it.
level2 | 1 | 32Glass level of the block (1 lightest, 3 most opaque).
labelsPartial<CodeBlockLabels>defaultCodeBlockLabelsEvery other string, for translation: labels={{ copy: "…" }}; omitted keys keep the English of defaultCodeBlockLabels. All 10 keys of CodeBlockLabels are listed in the key table under the props table.
code (required)stringNoneThe source. Leading blank lines and trailing whitespace are trimmed.
language(string & {}) | CodeLanguage"text"ts, tsx, js, jsx, json, css, bash, python, html, text (or an alias like "typescript", "sh").
filenameReactNodeNoneFile name shown as a tab in the header (e.g. "app/page.tsx").
iconReactNodea file, or a terminal for shellIcon before the file name (defaults to a file, or a terminal for shell).
headerbooleantrueShow the header bar (file name, language, wrap, copy). Without it, copy floats top-right.
CodeBlockLabels keys and English defaults (10)
Pass any key in labels; the rest keep the defaults of defaultCodeBlockLabels.
KeyEnglish default
copyCopy
copyCodeCopy code
copiedCopied
copiedAnnouncementCode copied to clipboard
copyFailedCopy failed
copyFailedAnnouncementCouldn't copy automatically. The code is selected: press Control C or Command C to copy it.
wrapWrap long lines
regionCode
tabsFiles
languages{ ts: "TypeScript", tsx: "TSX", js: "JavaScript", jsx: "JSX", json: "JSON", css: "CSS", bash: "Shell", pyth...

CodeBlockTabs

PropTypeDefaultDescription
onCopy(ClipboardEventHandler<HTMLDivElement> & ((code: string) => void))NoneCalled after a successful copy, with the copied text.
labelsPartial<CodeBlockLabels>defaultCodeBlockLabelsEvery other string, for translation: labels={{ copy: "…" }}; omitted keys keep the English of defaultCodeBlockLabels. All 10 keys of CodeBlockLabels are listed in the key table under the props table.
wrapbooleanNoneControlled wrapping of long lines.
showLineNumbersbooleantrue when there is more than one lineShow line numbers.
startLineNumbernumber1Number of the first line (for excerpts of a longer file).
defaultWrapbooleanfalseSets the starting wrap state when uncontrolled.
onWrapChange((wrap: boolean) => void)NoneCalled with the new value when the wrap toggle is pressed.
showWrapTogglebooleantrueShow the wrap toggle in the header.
copyablebooleantrueShow the copy button.
maxHeightstring | number"32rem"Taller code scrolls inside. A number is px; "none" never limits it.
level2 | 1 | 32Glass level of the block (1 lightest, 3 most opaque).
files (required)CodeBlockFile[]NoneThe tabs to show, in order.
valuestringNoneControlled active tab (a file label).
defaultValuestringthe firstInitially active tab when uncontrolled (defaults to the first).
onValueChange((label: string) => void)NoneCalled with the label of the tab that was just selected.

Theming tokens

PropTypeDefaultDescription
--sheen-code-keywordcolortokens.cssAlso: string, number, literal, function, type, tag, attr, property, variable, comment, punctuation.
DefaultsNoneEach >= 4.5:1 on the block's glass and on highlighted, added and removed lines, in light and dark. Override on the block or any ancestor.

Keyboard

KeysAction
TabReach the wrap toggle and the copy button.
Enter/SpacePress the focused button.
Arrow keysScroll the code once it is focused; it is focusable only when it actually scrolls.
Arrow Left/Arrow Right, Home/EndCodeBlockTabs: move between file tabs.

Accessibility

  • The code area is a named region ("Code: button.tsx"). Line numbers and diff markers are not read or copied; diff lines also carry +/- text.
  • Copy announces "Code copied" politely; if copying fails, the code is selected for manual copy.
  • Code is always left to right and translate="no". Syntax colors keep 4.5:1 on glass in light and dark.

All exports on this page

  • CodeBlock — Syntax-highlighted code on glass, with no highlighting dependency (a small built-in tokenizer for ts, tsx, js, jsx, json, css, bash, python and html).
  • CodeBlockTabs — Several files (or one command for several package managers) in one block.
  • defaultCodeBlockLabels — The English strings of CodeBlock and CodeBlockTabs.
  • parseLineSpec — Turn a LineSpec ("1, 4-6" or [1, 4, 5, 6]) into a set of 1-based line numbers.

When to use the code block

  • Use it as a syntax highlighter in documentation and blog posts to show a file with a filename tab, line numbers and highlightLines for the two or three lines the paragraph is explaining.
  • Use addedLines and removedLines to show a migration or a diff, since the lines render as ins and del elements with plus and minus markers, so color is never the only signal.
  • Use CodeBlockTabs for an install command in npm, pnpm and yarn, or the same snippet in several languages, with one copy and wrap control acting on the active tab.
  • Skip it when users need to edit or run the code; it is a read-only display, so a real editor or sandbox fits, and Kbd is the right tool for a single key or short inline command.
  • Pair it with Tabs-style CodeBlockTabs for variants, Toast for your own copy confirmation through onCopy, and GlassCard or Accordion to group long examples.

Frequently asked questions

67 components pages in all: browse them on All components.

By Lokendra Singh Rathore (GitHub, opens in a new tab). Published , updated .