Skip to content
CraftDocs
GitHub
Home
Home
Changelog
What's New
Guide
Guide
Getting Started
Principles
Styling Components
Theme System
Foundations
All Tokens
Color
Elevation
Icons
Motion
Shape
Spacing
Typography
Libraries
Libraries
@xds/cli
@xds/core
Themes
Themes
Theme: daily
Default Theme
Theme: matcha
Neutral Theme
Components
Components
AppShell
AspectRatio
Avatar
Avatar
AvatarStatusDot
Badge
Banner
Breadcrumbs
BreadcrumbItem
Breadcrumbs
Button
Button
IconButton
ToggleButton
ToggleButtonGroup
Calendar
Card
Carousel
Chat
ChatComposer
ChatComposerDrawer
ChatComposerInput
ChatComposerTokenElement
ChatDictationButton
ChatLayout
ChatLayoutScrollButton
ChatMessage
ChatMessageBubble
ChatMessageList
ChatMessageMetadata
ChatSendButton
ChatSystemMessage
ChatTokenizedText
ChatToolCalls
Checkbox
CheckboxInput
CheckboxList
CheckboxListItem
ClickableCard
Code
CodeBlock
Collapsible
Collapsible
CollapsibleGroup
useXDSCollapsible
CommandPalette
CommandPalette
CommandPaletteEmpty
CommandPaletteFooter
CommandPaletteGroup
CommandPaletteInput
CommandPaletteItem
CommandPaletteList
DateInput
Dialog
AlertDialog
Dialog
DialogHeader
useXDSImperativeAlertDialog
useXDSImperativeDialog
Divider
DropdownMenu
DropdownMenu
DropdownMenuDivider
DropdownMenuItem
DropdownMenuItemData
DropdownMenuSection
EmptyState
Field
Field
FieldLabel
FieldStatus
Heading
HoverCard
Icon
Kbd
Layout
Center
FormLayout
Grid
GridSpan
HStack
Layout
LayoutContainer
LayoutContent
LayoutFooter
LayoutHeader
LayoutPanel
Section
StackItem
VStack
Link
List
List
ListItem
Markdown
MetadataList
MetadataList
MetadataListItem
MobileNav
MoreMenu
NavIcon
NavMenuItem
NumberInput
OverflowList
Pagination
Popover
PowerSearch
ProgressBar
Radio
RadioList
RadioListItem
Resizable
ResizeHandle
useXDSResizable
SegmentedControl
SegmentedControl
SegmentedControlItem
SelectableCard
Selector
MultiSelector
Selector
SelectorOption
SideNav
SideNav
SideNavCollapseButton
SideNavHeading
SideNavItem
SideNavSection
Skeleton
Slider
Spinner
StatusDot
Switch
Table
BaseTable
Table
TableCell
TableHeaderCell
TableRow
useXDSTableColumnSettings
useXDSTablePagination
useXDSTableSelection
useXDSTableSelectionState
useXDSTableSortable
Tabs
Tab
TabList
TabMenu
Text
TextArea
TextInput
Thumbnail
TimeInput
Timestamp
Toast
Toast
useXDSToast
Token
Tokenizer
Toolbar
Tooltip
TopNav
TopNav
TopNavHeading
TopNavItem
TopNavMegaMenu
TopNavMegaMenuFeaturedCard
TopNavMegaMenuItem
TopNavMenu
TreeList
Typeahead
BaseTypeahead
Typeahead
TypeaheadItem
useXDSHoverCard
useXDSPopover
useXDSTooltip
Utilities
Utilities
LinkProvider
MediaTheme
SyntaxTheme
Theme
useClickableContainer
useEntryAnimation
useFocusTrap
useGridFocus
useImageMode
useInputContainer
useListFocus
useMediaQuery
useOverflow
useScrollLock
useScrollOverflow
useXDSLayer
useXDSStreamingText
Terms of UsePrivacy Policy
Type to search
↑↓Navigate↵SelectEscClose
CodeBlock@xds/core · XDSCodeBlock v0.0.13

Usage

CodeBlock renders syntax-highlighted code with line numbers, a copy button, and optional collapsible sections. Use XDSCodeBlock for multi-line snippets like source files, terminal commands, and configuration examples. Use XDSCode for inline references to function names, variables, or CLI flags within body text.
ts
import {XDSCodeBlock} from '@xds/core/CodeBlock'

Best practices

GuidancePractices
DoSet the language prop to match the code content so syntax highlighting is accurate. Use "plaintext" when the language is unknown.
DoAdd a title when the code represents a file — it gives readers context and appears in the header bar alongside the copy button.
DoUse XDSCode for short inline references like function names or CLI flags, and XDSCodeBlock for standalone multi-line snippets.
Don'tEnable line numbers on short snippets (under 5 lines) where they add clutter without helping navigation.
Don'tNest a code block inside a scrollable container — use the maxHeight prop instead, which handles overflow natively.

Sub-components

CodeBlock is a compound component with 2 sub-components.

XDSCode

Inline code element. Renders a styled <code> with monospace font and muted background. For fenced blocks, use XDSCodeBlock.
PropTypeDescription
childrenrequired
ReactNodeCode content.
xstyle
StyleXStylesStyleX styles for layout customization. Must be a stylex.create() value.
className
stringCSS class name for the root element. Prefer xstyle for styling.
style
CSSPropertiesInline styles. Prefer xstyle for StyleX-optimized styling.
data-testid
stringTest selector for automated testing frameworks.

XDSCodeBlock

Fenced code block with syntax highlighting. Use for multi-line code snippets.
PropTypeDescription
coderequired
stringThe code string to display.
language
string (default: 'plaintext')Language for syntax highlighting. Use "plaintext" to disable.
title
stringFilename or label shown in the header bar.
hasLanguageLabel
boolean (default: true)Show the language name in the header bar. Hidden when language is "plaintext".
hasLineNumbers
boolean (default: false)Show a line number gutter.
highlightLines
number[]1-indexed line numbers to highlight.
hasCopyButton
boolean (default: true)Show a copy-to-clipboard button.
onCopy
() => voidCallback after the code is copied.
isWrapped
boolean (default: false)Wrap long lines instead of enabling horizontal scroll.
maxHeight
number | stringMax height before the block scrolls vertically.
size
'sm' | 'md' (default: 'md')Text size variant.
tokenizer
(code: string, language: string) => Array<{type: string; start: number; end: number}>Custom tokenizer override for unsupported languages.
isCollapsible
boolean (default: false)Allow collapsing the code body into just the header bar. Starts expanded; the header becomes clickable to toggle. Only shows the toggle when the code exceeds collapsibleThreshold lines.
collapsibleThreshold
number (default: 10)Minimum number of lines before the collapse toggle appears. Below this threshold the code block renders normally even when isCollapsible is true.
xstyle
StyleXStylesStyleX styles for layout customization. Must be a stylex.create() value.
className
stringCSS class name for the root element. Prefer xstyle for styling.
style
CSSPropertiesInline styles. Prefer xstyle for StyleX-optimized styling.
data-testid
stringTest selector for automated testing frameworks.

Examples

Common configurations, variations, and states.
Code — ConfigA JSON configuration file with a title bar and line numbers. The title prop adds a filename label in the header so readers know which file the code belongs to.
tsx
'use client';
​
import {XDSCodeBlock} from '@xds/core/CodeBlock';
​
const code = `{
"name": "@xds/core",
"version": "0.0.5",
"dependencies": {
"@stylexjs/stylex": "^0.17.5",
"react": "^19.0.0"
},
"scripts": {
"build": "tsup",
"test": "vitest"
}
}`;
​
export default function CodeBlockJSONConfig() {
return (
<XDSCodeBlock
code={code}
language="json"
title="package.json"
hasLineNumbers
/>
);
}
Code — HighlightedTypeScript code with specific lines highlighted to draw attention to a key section. Use highlightLines to call out new or important code in tutorials and changelogs.
tsx
'use client';
​
import {XDSCodeBlock} from '@xds/core/CodeBlock';
​
const code = `import {useState, useEffect} from 'react';
​
interface User {
id: string;
name: string;
email: string;
}
​
async function fetchUser(id: string): Promise<User> {
const response = await fetch(\`/api/users/\${id}\`);
if (!response.ok) {
throw new Error(\`HTTP \${response.status}\`);
}
return response.json();
}
​
export function useUser(id: string) {
const [user, setUser] = useState<User | null>(null);
​
useEffect(() => {
fetchUser(id).then(setUser);
}, [id]);
​
return user;
}`;
​
export default function CodeBlockHighlightedLines() {
return (
<XDSCodeBlock
code={code}
language="typescript"
title="useUser.ts"
hasLineNumbers
highlightLines={[9, 10, 11, 12, 13]}
/>
);
}
Code — ScrollableA long code block with a max height that enables vertical scrolling. Use maxHeight to keep the block from dominating the page when displaying large files.
tsx
'use client';
​
import {XDSCodeBlock} from '@xds/core/CodeBlock';
​
const code = Array.from(
{length: 50},
(_, i) => `const line${i + 1} = ${i + 1};`,
).join('\n');
​
export default function CodeBlockScrollableBlock() {
return (
<XDSCodeBlock
code={code}
language="typescript"
title="many-lines.ts"
hasLineNumbers
maxHeight="100%"
/>
);
}
Code — SnippetShort terminal commands with a copy button and no line numbers. Use for install instructions or one-liner commands that readers will paste directly.
tsx
'use client';
​
import {XDSCodeBlock} from '@xds/core/CodeBlock';
import {XDSVStack} from '@xds/core/Stack';
​
export default function CodeBlockBashCommand() {
return (
<XDSVStack gap={4}>
<XDSCodeBlock
code="npm install @xds/core @stylexjs/stylex"
language="bash"
hasCopyButton
/>
<XDSCodeBlock
code={`curl -s https://api.example.com/status | jq '.services[] | select(.healthy == false)'`}
language="bash"
hasCopyButton
/>
</XDSVStack>
);
}

Showcase source

tsx
'use client';
​
import {XDSCodeBlock} from '@xds/core/CodeBlock';
​
const code = `import {useState, useEffect} from 'react';
​
export function useUser(id: string) {
const [user, setUser] = useState<User | null>(null);
​
useEffect(() => {
fetch(\`/api/users/\${id}\`)
.then(res => res.json())
.then(setUser);
}, [id]);
​
return user;
}`;
​
export default function CodeBlockShowcase() {
return (
<XDSCodeBlock
code={code}
language="typescript"
title="useUser.ts"
hasLineNumbers
hasCopyButton
/>
);
}