Developer

Code Block

Readable syntax, honest copy feedback, and safe source rendering.

OSCL StudioComponents, in context.Live preview
FOUNDATION / DEVELOPER

Code Block

hello.tsx
import { Button } from "oscl-ui";

<Button>Build something</Button>
Interactive preview. Real components.View docs

Use it in your project

Install oscl-ui from npm and import oscl-ui/styles.css once. See installation.

code-block-example.tsx
import { CodeBlock } from "oscl-ui";

<CodeBlock language="bash" code="npm install oscl-ui" />

Accessibility

Keep visible labels and keyboard focus. Supply an accessible name to icon-only actions. Try this preview with Tab, Enter, Space, and Escape where appropriate.

The source, in full

This is the actual source from the isolated OSCL package used by this website. Native props and TypeScript declarations are included in the npm package.

code-block.tsx
"use client";

import { useMemo } from "react";
import hljs from "highlight.js/lib/core";
import javascript from "highlight.js/lib/languages/javascript";
import typescript from "highlight.js/lib/languages/typescript";
import json from "highlight.js/lib/languages/json";
import bash from "highlight.js/lib/languages/bash";
import css from "highlight.js/lib/languages/css";
import { CopyButton } from "./copy-button.js";

hljs.registerLanguage("javascript", javascript);
hljs.registerLanguage("typescript", typescript);
hljs.registerLanguage("json", json);
hljs.registerLanguage("bash", bash);
hljs.registerLanguage("css", css);

export interface CodeBlockProps {
  code: string;
  language?: "typescript" | "tsx" | "javascript" | "jsx" | "json" | "bash" | "css" | "text";
  filename?: string;
  className?: string;
}
export function CodeBlock({ code, language = "tsx", filename, className = "" }: CodeBlockProps) {
  const syntaxLanguage = language === "tsx" ? "typescript" : language === "jsx" ? "javascript" : language;
  const highlighted = useMemo(() => syntaxLanguage === "text" ? null : hljs.highlight(code, { language: syntaxLanguage, ignoreIllegals: true }).value, [code, syntaxLanguage]);
  return <div className={`oscl-code-block ${className}`}>
    <div className="oscl-code-header"><span>{filename || language}</span><CopyButton value={code} label="Copy code" /></div>
    <pre className="oscl-code" tabIndex={0} aria-label={`${filename || language} source code`}><code>
      {highlighted === null ? code : <span dangerouslySetInnerHTML={{ __html: highlighted }} />}
    </code></pre>
  </div>;
}