Code Block
Display readable code with an optional caption and action.
Usage
Compose CodeBlock with CodeBlockHeader, CodeBlockCaption and CodeBlockContent. CodeBlockCopy is a native button; the consumer owns copying and feedback.
Accessibility
Label copy actions and announce the result. A named, focusable code region lets keyboard users scroll long lines. Preserve whitespace and syntax markup.
| Property | Type | Default |
|---|---|---|
| children | ReactNode | None |
| tabIndex (Content) | number | Native default |
| onClick (Copy) | MouseEventHandler | None |
| type (Copy) | button | submit | reset | button |
const Example = () => {
const code = 'pnpm add @oddmash/ui';
const [status, setStatus] = useState('');
const copy = async () => {
try {
await navigator.clipboard.writeText(code);
setStatus('Copied');
} catch {
setStatus('Select the code to copy');
}
};
return (
<CodeBlock>
<CodeBlockHeader>
<CodeBlockCaption>Terminal</CodeBlockCaption>
<CodeBlockCopy onClick={copy}>Copy code</CodeBlockCopy>
</CodeBlockHeader>
<CodeBlockContent tabIndex={0} role="region" aria-label="Terminal code">
<code>{code}</code>
</CodeBlockContent>
<span role="status">{status}</span>
</CodeBlock>
);
};