2023-12-29T07:25:04.928Z

How to render a code block?

In this guide, I'll walk you through the steps to set up a basic code highlighter-renderer for your React application.

As I began constructing my new website, the idea of including a section with code snippets occurred to me. This could be a helpful resource for others or simply a space to showcase some of the cool things I've built - you never know when you might need them again.

However, I soon realized the need for a nice and easy way to display code on my own page. After some research, I found , which does exactly what I was looking for - and in a really easy way!

To start, you'll need to install the corresponding dependency:

# npm
npm install --save prism-react-renderer
# yarn
yarn add prism-react-renderer
# pnpm
pnpm add prism-react-renderer

After importing the Highlight component and the themes from the package, you can create a basic wrapper for a new component. In this case, let's call it CodeBlock.

'use client'
import { Highlight, themes } from 'prism-react-renderer'
import React from 'react'
type CodeBlockProps = {
code: string
language?: string // You will find a link with all supported languages later on
}
export const CodeBlock = ({ code, language = 'tsx' }: CodeBlockProps) => {
return (
<Highlight theme={themes.vsDark} code={code} language={language}>
{({ style, tokens, getLineProps, getTokenProps }) => (
<pre style={style}>
{tokens.map((line, i) => (
<div key={i} {...getLineProps({ line })}>
{line.map((token, key) => (
<span key={key} {...getTokenProps({ token })} />
))}
</div>
))}
</pre>
)}
</Highlight>
)
}

Finally, pass a string to the component, and it will display the formatted code. 🚀

// Supposing a list of elements with an id and a title
const code = `
<div>
{list.map(li => <span key={li.id}>{li.title}</span>)}
</div>
`
<CodeBlock code={code} />

The output for that will be:

<div>
{list.map(li => <span key={li.id}>{li.title}</span>)}
</div>

Find all available languages

0