A code block highlighted with Shiki that can type its code out, character by character.
Installation
The code is highlighted with Shiki, a peer dependency of this primitive, loaded on demand:
Usage
import { CodeBlock } from '@animate-ui/react/primitives/code-block';
export function Snippet() {
return (
<CodeBlock
code="console.log('Hello, world!');"
lang="javascript"
writing
duration={2000}
/>
);
}The block renders Shiki's <pre> inside a div. Style it through that div ([&_pre]:…, [&_.line]:…); data-writing and data-done let you show a cursor while it types.
Ready-made block
A styled block around the primitive, with a cursor while it types and a copy button, is a file you add to your project and own:
import { CodeBlock } from '@/components/animate-ui/components/code-block';
export function Snippet() {
return (
<CodeBlock
code="console.log('Hello, world!');"
lang="javascript"
writing
duration={2000}
/>
);
}It takes every prop of the primitive, plus:
| Prop | Type | Default |
|---|---|---|
cursor? | boolean | true |
copyButton? | boolean | true |
scrollClassName? | string | - |
Animation
- With
writing, the code appears one character at a time, evenly overduration(afterdelay), and the block andscrollContainerRef(its parent element by default) scroll smoothly to follow the last line. - With
inView, writing starts when the block scrolls into view. - Under reduced motion, the whole code is shown at once (
onDoneis still called).
API Reference
CodeBlock
| Prop | Type | Default |
|---|---|---|
code | string | - |
lang | string | - |
theme? | "light" | "dark" | "light" |
themes? | { light: string; dark: string } | { light: "github-light", dark: "github-dark" } |
writing? | boolean | false |
duration? | number | 5000 |
delay? | number | 0 |
onDone? | () => void | - |
onWrite? | (info: { index: number; length: number; done: boolean }) => void | - |
scrollContainerRef? | React.RefObject<HTMLElement | null> | - |
inView? | boolean | false |
inViewMargin? | string | "0px" |
inViewOnce? | boolean | true |
...props? | React.ComponentProps<'div'> | - |