Syntax-highlighted code blocks with language labels and copy actions for AI markdown.
Syntax-highlighted code blocks with language labels and copy actions for AI markdown.
import { CodeBlock } from 'heroui-native-pro';Highlighting runs natively through the optional react-native-enriched-markdown peer (tree-sitter grammars). Without it, CodeBlock.Code renders plain monospace text and warns once in development.
npx expo install react-native-enriched-markdownjson, javascript, typescript, tsx, python, bash, go, rust, java, c, css, html, markdown, and yaml. Trim it through the enriched-markdown block of your app's package.json to reduce binary size. Languages without a compiled grammar render uncolored.onlyBuiltDependencies (in package.json under pnpm, or in pnpm-workspace.yaml) and reinstall:{
"pnpm": {
"onlyBuiltDependencies": ["react-native-enriched-markdown"]
}
}<CodeBlock>
<CodeBlock.Header>
...
<CodeBlock.CopyButton code="..." onCopy={...} />
</CodeBlock.Header>
<CodeBlock.Code code="..." language="..." />
</CodeBlock>surface-secondary tone. Cascades animation="disable-all" and mounts the theme background layer (glass). The card has no vertical margin; spacing belongs to the parent's gap.background prop.maxLines collapses long code behind "Show more". The code stays left-to-right in RTL layouts.onCopy and swaps to a check mark for two seconds.<CodeBlock>
<CodeBlock.Header>
typescript
<CodeBlock.CopyButton code={code} onCopy={Clipboard.setStringAsync} />
</CodeBlock.Header>
<CodeBlock.Code code={code} language="typescript" />
</CodeBlock>React Native has no clipboard API, so CodeBlock.CopyButton does not copy by itself. Pass onCopy and write the code with expo-clipboard, @react-native-clipboard/clipboard, or your own module. The check mark shows once onCopy resolves; a rejected promise keeps the copy glyph.
import * as Clipboard from 'expo-clipboard';
<CodeBlock.CopyButton
code={code}
accessibilityLabel="Copy code"
onCopy={Clipboard.setStringAsync}
/>maxLines shows the first lines and a "Show more" toggle. It counts source lines, not wrapped lines. Use the controlled isExpanded / onExpandedChange in virtualized lists so the state survives recycling. Localize the toggle with showMoreLabel / showLessLabel.
<CodeBlock.Code
code={code}
language="typescript"
maxLines={10}
showMoreLabel="Show more"
showLessLabel="Show less"
/>maxScrollHeight caps the code area. Taller code scrolls inside it while the header and the "Show more" toggle stay in place. Combine it with maxLines to expand a long block into a bounded area rather than growing the screen. The scroll area scrolls first while it has room, then hands the gesture to the parent scroll view.
const { height } = useWindowDimensions();
<CodeBlock>
<CodeBlock.Header>
use-forecast.ts
<CodeBlock.CopyButton code={code} onCopy={Clipboard.setStringAsync} />
</CodeBlock.Header>
<CodeBlock.Code
code={code}
language="typescript"
maxLines={10}
maxScrollHeight={height * 0.5}
/>
</CodeBlock>Long lines wrap by default. Set isWrapped={false} to keep every source line on one row and scroll the code sideways instead, for structured code such as JSON, tables, or logs. The scroller reaches the card's edges, which fade while more code is hidden. maxLines then counts exactly the rows on screen.
<CodeBlock.Code code={json} language="json" isWrapped={false} maxLines={12} />Set isHighlighted={false} to skip highlighting, for example for logs or partial JSON that is still streaming.
<CodeBlock.Code code={log} isHighlighted={false} />The highlighted renderer is a native text view, so users can select part of the code with the system handles. markdownTextProps forwards props to it (EnrichedMarkdownText): add items to the selection menu with contextMenuItems, tint the selection with selectionColor, or react to taps with onCodeBlockPress.
<CodeBlock.Code
code={code}
language="python"
markdownTextProps={{
selectionColor: accentColor,
contextMenuItems: [
{ text: 'Explain', icon: 'sparkles', onPress: ({ text }) => explain(text) },
{ text: 'Search docs', onPress: ({ text }) => searchDocs(text) },
],
}}
/>markdownStyle is deep-merged over the component style (including codeBlock.syntaxColors).containerStyle is combined with the left-to-right pin.selectionMenuConfig defaults to { copyAsMarkdown: { enabled: false } }, so "Copy as Markdown" does not copy the code with its fence. The system "Copy" stays.contextMenuItems needs iOS 16+, and its icon (an SF Symbol) is iOS-only.isHighlighted={false}) ignores markdownTextProps. Use textProps there.Code uses the GitHub Light / Dark palette, picked by the card's brightness rather than the color scheme. Default colors are deepened to reach minContrastRatio (default 4.5) against the card; set it to 0 for the exact GitHub colors. Override tokens with syntaxColors and the text with classNames.text; overrides are used as given. The text slot's typography (font-size, line-height, color, font-family) styles both renderers.
<CodeBlock className="bg-[#282C34]">
<CodeBlock.Header classNames={{ label: 'text-[#ABB2BF]' }}>python</CodeBlock.Header>
<CodeBlock.Code
code={code}
language="python"
classNames={{ text: 'text-[#ABB2BF]' }}
syntaxColors={{ keyword: '#C678DD', string: '#98C379', comment: '#7F848E' }}
/>
</CodeBlock>The root renders CodeBlock.Background when the active theme provides one (for example glass). Pass a node to background to replace it, or null to remove it.
<CodeBlock background={<CodeBlock.Background>...</CodeBlock.Background>}>
...
</CodeBlock>
<CodeBlock background={null}>...</CodeBlock>import * as Clipboard from 'expo-clipboard';
import { ChatMessage, CodeBlock } from 'heroui-native-pro';
import { View } from 'react-native';
const TYPESCRIPT_CODE = `function greet(name: string) {
return \`Hello, \${name}!\`;
}
console.log(greet("HeroUI"));`;
const copyToClipboard = async (code: string) => {
await Clipboard.setStringAsync(code);
};
export default function CodeBlockExample() {
return (
<View className="flex-1 px-5 items-center justify-center">
<View className="w-full gap-4">
<ChatMessage.Assistant>
<ChatMessage.Avatar alt="Assistant" fallback="AI" />
<ChatMessage.Body>
<ChatMessage.Content>
Here is a small helper that greets a user by name:
</ChatMessage.Content>
<CodeBlock>
<CodeBlock.Header>
typescript
<CodeBlock.CopyButton
code={TYPESCRIPT_CODE}
accessibilityLabel="Copy code"
onCopy={copyToClipboard}
/>
</CodeBlock.Header>
<CodeBlock.Code code={TYPESCRIPT_CODE} language="typescript" />
</CodeBlock>
</ChatMessage.Body>
</ChatMessage.Assistant>
</View>
</View>
);
}| prop | type | default | description |
|---|---|---|---|
children | ReactNode | - | Parts of the block, usually CodeBlock.Header and CodeBlock.Code |
className | string | - | Additional CSS classes for the card. Its background color drives the syntax palette |
background | ReactNode | - | Background layer: undefined uses the theme default, a node replaces it, null removes it |
animation | CodeBlockRootAnimation | - | "disable-all" cascades the disabled state to the copy button glyph |
...ViewProps | ViewProps | - | All standard React Native View props are supported |
| type | description |
|---|---|
undefined | Default animations |
'disable-all' | Disables all animations, cascaded to animated descendants |
Without children, the active theme decides its content (a frosted blur under glass, nothing otherwise).
| prop | type | default | description |
|---|---|---|---|
children | ReactNode | - | Custom background content |
className | string | - | Additional CSS classes |
...ViewProps | ViewProps | - | All standard React Native View props are supported |
| prop | type | default | description |
|---|---|---|---|
children | ReactNode | - | Text runs render as a muted uppercase label; other nodes as-is |
className | string | - | Additional CSS classes for the container |
classNames | ElementSlots<HeaderSlots> | - | Additional CSS classes for the slots |
styles | CodeBlockHeaderStyles | - | Inline styles for the slots |
...ViewProps | ViewProps | - | All standard React Native View props are supported |
ElementSlots<HeaderSlots>| prop | type | description |
|---|---|---|
container | string | Row hosting the label and actions |
label | string | Muted Text wrapping every run of string / number children |
styles| prop | type | description |
|---|---|---|
label | TextStyle | Style of the label Text |
The container takes the regular style prop.
| prop | type | default | description |
|---|---|---|---|
code | string | - | Source code |
maxLines | number | - | Source lines shown before "Show more". undefined shows every line |
maxScrollHeight | number | - | Max height of the code area in pixels; taller code scrolls, header and toggle stay |
isWrapped | boolean | true | Whether long lines wrap; false scrolls them sideways with faded edges |
language | string | 'plaintext' | Markdown fence info string selecting the grammar |
isExpanded | boolean | - | Controlled expanded state of the toggle |
defaultExpanded | boolean | false | Expanded state on mount |
isHighlighted | boolean | true | Whether syntax highlighting is applied |
isSelectable | boolean | true | Whether the code can be selected with the system text menu |
className | string | - | Additional CSS classes for the container |
classNames | ElementSlots<CodeSlots> | - | Additional CSS classes for the slots |
styles | CodeBlockCodeStyles | - | Inline styles for the slots |
syntaxColors | CodeBlockSyntaxColors | - | Color overrides per syntax token, used as given |
minContrastRatio | number | 4.5 | Minimum contrast of the default code colors against the card; 0 keeps exact GitHub colors |
showMoreLabel | string | 'Show more' | Toggle label while collapsed |
showLessLabel | string | 'Show less' | Toggle label while expanded |
textProps | Omit<TextProps, 'children' | 'selectable'> | - | Props forwarded to the plain Text renderer |
markdownTextProps | CodeBlockMarkdownTextProps | - | Props forwarded to the highlighted renderer |
onExpandedChange | (isExpanded: boolean) => void | - | Called when the toggle changes the expanded state |
...ViewProps | Omit<ViewProps, 'children'> | - | All standard React Native View props except children |
ElementSlots<CodeSlots>| prop | type | description |
|---|---|---|
container | string | Padded View hosting the code and the toggle |
text | string | Code typography. Also reaches the highlighted renderer |
scroll | string | ScrollView bounding the code (maxScrollHeight only) |
lineScroll | string | Horizontal scroller of unwrapped lines (isWrapped={false} only) |
lineScrollContent | string | Content of the horizontal scroller (isWrapped={false} only) |
showMore | string | "Show more" / "Show less" pressable row |
showMoreLabel | string | Label Text inside the toggle |
styles| prop | type | description |
|---|---|---|
container | ViewStyle | Padded container |
text | TextStyle | Code Text (plain renderer only) |
scroll | ViewStyle | Code scroll area (maxScrollHeight only) |
lineScroll | ViewStyle | Horizontal line scroller (isWrapped={false} only) |
lineScrollContent | ViewStyle | Line scroller's content (isWrapped={false} only) |
showMore | ViewStyle | "Show more" row |
showMoreLabel | TextStyle | "Show more" label |
Partial<Record<CodeBlockSyntaxToken, string>>. Tokens left out keep the default GitHub color.
CodeBlockSyntaxToken: keyword, operator, punctuation, string, number, constant, comment, function, type, variable, property, tag, attribute, embedded.
EnrichedMarkdownTextProps without markdown, flavor, numberOfLines, ellipsizeMode, allowTrailingMargin, md4cFlags, streamingAnimation, and streamingConfig, which the component owns. Examples: contextMenuItems, selectionMenuConfig, selectionColor, onCodeBlockPress, enableBlockContextMenu, accessibilityLabels.
| prop | type | default | description |
|---|---|---|---|
code | string | - | Code passed to onCopy |
isDisabled | boolean | false | Whether the button is disabled |
className | string | - | Additional CSS classes for the button |
classNames | ElementSlots<CopyButtonSlots> | - | Additional CSS classes for the slots |
style | ViewStyle | - | Inline style of the button |
iconProps | CodeBlockCopyButtonIconProps | - | Props of the copy / check glyphs |
accessibilityLabel | string | 'Copy code' | Accessibility label of the button |
onCopy | (code: string) => unknown | - | Writes the code to the clipboard. The check mark shows once it resolves |
animation | CodeBlockCopyButtonAnimation | - | Animation configuration of the glyph swap |
ElementSlots<CopyButtonSlots>| prop | type | description |
|---|---|---|
container | string | heroui-native ghost icon-only Button |
icon | string | View hosting the copy / check glyph |
| prop | type | default | description |
|---|---|---|---|
size | number | 14 | Size of the glyph, in pixels |
color | string | theme muted | Color of the glyph |
Animation configuration of the glyph swap. Can be:
true or undefined: the glyph zooms in when it swapsfalse or "disabled": the glyph swaps instantlyobject: custom entering / exiting animations| prop | type | default | description |
|---|---|---|---|
state | 'disabled' | boolean | - | Disable animations while customizing properties |
entering.value | EntryOrExitLayoutType | ZoomIn.springify().damping(120).stiffness(1200).mass(3).withInitialValues({ transform: [{ scale: 0.25 }] }) | Entering animation of the new glyph |
exiting.value | EntryOrExitLayoutType | FadeOut.duration(120).easing(Easing.in(Easing.ease)) | Exiting animation of the previous glyph |