Skip to main content

CodeBlock

Shows code with syntax colors, a copy button, and diff or collapse when you need them.

import { CodeBlock } from "@/fragments/ui";Source

Preview

<CodeBlock code={`import { Button } from '@usefragments/ui';

function App() {
  return <Button>Click me</Button>;
}`} language="tsx" />

Installation

npx @usefragments/cli add codeblock
pnpm add shiki

Writes src/fragments/ui/components/CodeBlock plus what it imports, the globals stylesheet, and .fragments/registry-lock.json, then prints the packages to add. No account, no key.

Your own registry: publish from Fragments Cloud and add --registry org/name. Connect a workspace.

Anatomy

CodeBlock is a compound: import the root and reach its parts through dot notation.

  • CodeBlock.Tabbed

Examples

With Filename

A header bar names the source file and holds the copy button.

<CodeBlock filename="app.tsx" code={`import { Button, Card } from '@usefragments/ui';

function App() {
  return (
    <Card>
      <Card.Header>Welcome</Card.Header>

With Title

A label above the block, outside the code surface.

<CodeBlock title="Installation" code="npm install @usefragments/ui" language="bash" />

With Caption

A footer line for the aside that does not belong in the code.

<CodeBlock
  code={`const API_URL = process.env.NEXT_PUBLIC_API_URL;`}
  language="typescript"
  caption="Environment variables must be prefixed with NEXT_PUBLIC_ to be available in the browser."
/>

With Line Numbers

Turn these on once a snippet is long enough to point at.

<CodeBlock code={`const greeting = "Hello";
const name = "World";
console.log(\`\${greeting}, \${name}!\`);`} language="typescript" showLineNumbers />

Custom Start Line

Numbering starts where the excerpt actually starts in the file.

<CodeBlock
  code={`  return (
    <button onClick={() => setCount(c => c + 1)}>
      Count: {count}
    </button>
  );

With Highlighted Lines

Marks the lines the prose is talking about.

<CodeBlock code={`import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (

Diff View

Added and removed lines, side by side with the rest.

<CodeBlock
  code={`import { useState } from 'react';
import { useCallback } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

Custom Theme

Any Shiki theme works — pass its name to theme.

<CodeBlock
  code={`async function fetchUser(id: string) {
  const response = await fetch(\`/api/users/\${id}\`);
  return response.json();
}`}
  language="typescript"

Word Wrap

Long lines break instead of scrolling sideways.

<CodeBlock
  code={`const longString = "This is a very long string that would normally cause horizontal scrolling, but with word wrap enabled it will break to the next line instead.";`}
  language="typescript"
  wordWrap
/>

Max Height with Scroll

Caps the height so one snippet cannot own the page.

<CodeBlock
  code={`// This code block has a maximum height
function processItems(items: string[]) {
  const results = [];
  for (const item of items) {
    if (item.startsWith('_')) {

Collapsible

Shows the opening lines and hides the rest behind a toggle.

<CodeBlock
  code={`import React, { useState, useEffect } from 'react';

interface User {
  id: string;
  name: string;

JSON

Config files highlight the same way source does.

<CodeBlock title="package.json" code={`{
  "name": "my-app",
  "dependencies": {
    "@usefragments/ui": "^0.3.0"
  }
}`} language="json" />

Without Copy Button

Drop the copy button when the snippet is not meant to be reused.

<CodeBlock code="const simple = true;" language="typescript" showCopy={false} />

API

Component props
Prop
Type
Default
Description
codeRequiredstringNot setThe code string to display
languageenumtsxtypescripttsjavascriptjsjsxbashshellcssscsssassjsonhtmlxmlmarkdownmdyamlymlpythonpyrubygorustjavakotlinswiftccppcsharpphpsqlgraphqldiffplaintexttexttsxProgramming language for syntax highlighting
themeenumcss-variablessynthwave-84github-darkgithub-lightone-dark-prodraculanordmonokaivitesse-darkvitesse-lightmin-darkmin-lightcss-variablesSyntax highlighting theme. css-variables maps spans onto --fui-code-token-* so both themes stay readable.
showCopybooleantrueWhether to show the copy button
titlestringNot setOptional title displayed above the code block (external label)
filenamestringNot setOptional filename shown in header bar inside code block
captionstringNot setOptional caption displayed below the code block
showLineNumbersbooleanfalseWhether to display line numbers
startLineNumbernumber1Starting line number (useful for code excerpts)
highlightLinesarrayNot setLines to highlight (e.g., [1, 3, "5-7"])
addedLinesarrayNot setLines marked as added in diff view (e.g., [2, "4-6"])
removedLinesarrayNot setLines marked as removed in diff view (e.g., [1, 3])
wordWrapbooleanfalseEnable word wrapping for long lines
maxHeightnumberNot setMaximum height in pixels (enables scrolling)
collapsiblebooleanfalseAllow collapsing/expanding the code block
defaultCollapsedbooleanfalseInitial collapsed state (only applies when collapsible is true)
collapsedLinesnumber5Number of lines to show when collapsed
collapseActionenumlinesexpandlinesCollapse control copy: line-count bar, or a single Expand / Collapse control
compactbooleanfalseCompact mode with reduced padding
persistentCopybooleanfalseShow a persistent copy button that is always visible
copyPlacementenumautoheaderoverlayautoWhere to place the copy button when not using persistentCopy
bgstringNot setCustom background color for the code block (useful when the content area is pure black or dark gray)
onCopyfunctionNot setCallback fired when the copy button is clicked and copy succeeds

Accessibility

  • Renders as semantic pre and code
  • The copy button is labelled and keyboard reachable
  • The collapse toggle reports aria-expanded

Guidance

Use when

  • Code examples inside prose or docs
  • Install and config snippets
  • Showing what changed, as a diff

Avoid when

  • The user needs to edit it (use an editor)
  • A couple of words inline (use a code element)
  • CardparentCan be wrapped in Card for additional context
  • TabschildUse in Tabs for showing code in multiple languages

Next steps