New product features | The latest in technology | The weekly debugging nightmares & more!
July 13, 2023
Take my knowledge and shove it up your brain...
If you're building a blog website for tech stuff, you will most likely need to add some code blocks to explain what you're talking about.
There are 2 approaches for this matter.
You can take a screenshot of your code using a vs code extension like CodeSnap
and just include the screenshot in your post like this:
And that would work fine, but the problem is that users won't be able to copy-paste the code, and most people like to just copy-paste stuff.
Place your code as actual text, but not only that, you also want your code to be styled like how you see it in vs code, and that's what we're going to achieve.
We need one package which is prismjs
You can install it by typing npm i prismjs
and now we're ready to go.
If you're building a blog website you're most likely using a CMS
in my case, I'm using Sanity
, but it doesn't matter as your code block is just a single string like this:
1const codeBlock = 2 "const myFunction = () => { \n console.log(`hello world`) \n }";
The \n
is automatically added when you paste your code in the CMS
.
All we need to do is import prismjs
and use it to highlight our code:
page.tsx
1import Prism from "prismjs";
2// This is the css file for the theme, it can be edited by going to node_modules\prismjs\themes or you can import a different theme from the same folder
3import "prismjs/themes/prism-coy.css";
4const codeBlock =
5 "const myFunction = () => { \n console.log(`hello world`) \n }";
6function page() {
7 return (
8 <div>
9 <pre className="dark:bg-gray-900 bg-gray-100 p-3 rounded-md overflow-auto ">
10 <code
11 dangerouslySetInnerHTML={{
12 __html: Prism.highlight(
13 codeBlock,
14 Prism.languages.javascript,
15 "javascript"
16 ),
17 }}
18 />
19 </pre>
20 </div>
21 );
22}
23
24export default page;
25
Now your code will look like this:
You can style it, however you like by editing the CSS file inside node_modules\prismjs\themes
or you can import a different file.
Notice I used dangerouslySetInnerHTML
, I know it's not recommended to use it, but this is the only way I could get this to work.
Also, I had to set the language manually, but if you're using a CMS
like sanity, they have a code block plugin that lets you specify your language, for each code block, so your code block becomes an object that contains your language and the actual code and you can pass that to prismjs
Next js 13 group routes is a game changer
This is a new feature in next js 13 that solves so many problems
Metadata guide in Next js 13
Next 13 introduced a new way to optimize your metadata, here's what you need to know
Next js 13 Route handlers explained
Forget the old api routes, this is the way
All you need to know about useOptimistic hook in Next js13
A new experimental feature from Next js 13 that will greatly imporove your UX