With React Server Components
Integrating React Code Block in a React Server Component environment is easy. If you are using Next.js 13+ and the App Router (opens in a new tab),
you can mark your CodeBlock component as a Client Component using 'use client'
directive and things should work as expected.
Why mark it as a Client Component?
Components exposed by React Code Block use React Context for sharing data, and it can only be used in Client Components. But you can still compose these Client Components in Server Components and enjoy its benefits of server rendering / not requiring client-side JavaScript(unless there are interactive elements in your code blocks).
Example
Create your own CodeBlock component and mark it as Client Component.
1'use client';2import { CodeBlock } from 'react-code-block';34function MyCodeBlock({ code, language }) {5return (6<CodeBlock code={code} language={language}>7<CodeBlock.Code className="bg-gray-900 p-6 rounded-xl shadow-lg">8<div className="table-row">9<CodeBlock.LineNumber className="table-cell pr-4 text-sm text-gray-500 text-right select-none" />10<CodeBlock.LineContent className="table-cell">11<CodeBlock.Token />12</CodeBlock.LineContent>13</div>14</CodeBlock.Code>15</CodeBlock>16);17}1819export default MyCodeBlock;
Use your <MyCodeBlock />
component normally in other Server / Client components.
1import MyCodeBlock from './MyCodeBlock';23export default function Home() {4return (5<div className="container mx-auto">6<MyCodeBlock code="console.log('Hello World!')" language="js" />7</div>8);9}
You can customize the CodeBlock component however you like with features such as line numbers, line highlighting, etc. as documented here.