Preview
Preparing…
Installation
shadcn/ui
shadcn/ui Command
pnpm dlx shadcn@latest add https://code-blocks.pheralb.dev/r/client-prismjs.jsonManual
Before creating the component, make sure you have the basic structure:
react
Code Block
The main structure of the Code Block component with header and content areas.
- Create your Prismjs highlighter utility:
prismjs
Prismjs Highlighter
The main highlighter utility to render syntax highlighted code with Prismjs.
- Create the Code Block Client component:
client-prismjs
"use client";
import type { ComponentProps } from "react";
import { cn } from "@/utils/cn";
import { highlight, type Languages } from "@/utils/prismjs/highlight";
interface CodeBlockPrismjsProps extends ComponentProps<"pre"> {
code: string;
language?: Languages;
lineNumbers?: boolean;
}
const CodeBlockPrismjs = ({
code,
language = "typescript",
className,
lineNumbers = false,
...props
}: CodeBlockPrismjsProps) => {
const highlightedHtml = highlight({ code, language });
return (
<pre
className={cn(
"w-full overflow-x-auto font-mono",
"p-3",
lineNumbers && "prism-line-numbers",
className,
)}
{...props}
>
<code dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
</pre>
);
};
export { CodeBlockPrismjs };Usage
Now you can use the CodeBlockPrismjs into your CodeBlockContent component:
import {
CodeBlock,
CodeBlockContent,
CodeBlockHeader,
CodeBlockGroup,
CodeBlockIcon,
} from "@/components/code-block";
import { CopyButton } from "@/components/code-block/copy-button";
import { CodeBlockPrismjs } from "@/components/code-block/client/prismjs";
<CodeBlock>
<CodeBlockHeader>
<CodeBlockGroup>
<CodeBlockIcon language="ts" />
<span>Code Block + Prismjs</span>
</CodeBlockGroup>
<CopyButton content={code} />
</CodeBlockHeader>
<CodeBlockContent>
<CodeBlockPrismjs
language="ts"
code="console.log('Hello, world!');"
/>
</CodeBlockContent>
</CodeBlock>;Props
React Props
| Prop | Type | Required | |
|---|---|---|---|
| code | string | Yes | |
| language | Languages | No | |
| lineNumbers | boolean | No | |
| Included: DOMAttributes | |||