Code Highlighting on Next.JS using PrismJS
Code highlighting on blog posts are important since it adds aesthetics to the blog post as well as it visualizes the code provided.
Installing PrismJS
There are many ways to add PrismJS on Next.JS. But in this blog, I opted to use the yarn package manager. You may also use npm package manager or a CDN. To add PrismJS using yarn package manager, simply use the command: yarn add prismjs
Adding PrismJS CSS
In order to style the code part, the PrismJS CSS must be loaded in the application. In your _app``.``js, add the line
import "prismjs/themes/prism-okaidia.css";
Your _app``.``js will look like this:
import "../styles/index.css";
import "prismjs/themes/prism-okaidia.css";
function MyApp({ Component, pageProps }) {
return <Component {…pageProps} />;
}
export default MyApp;
Adding PrismJS
In your blog post page, import the necessary files for PrismJs. In my case, the file is the [``slug``].``js located on pages``/``posts``/. The PrismJS files needed are the following:
import Prism from "prismjs";
import "prismjs/components/prism-javascript";
import "prismjs/components/prism-python";
Using PrismJS
Now, PrismJS can now be used to highlight code. For example we want to highlight the code:
export default function Posts(props) {
return (
<div className="container">
<p>Code Highlighting using PrismJS on Next.JS</p>
</div>
)
}
First we need to encode the code using Coder’s Toolbox. This is important so that characters like <, >, and ” will be read as texts, and not a codes or html tags. The code will look like this after encoding:
export default function Posts(props) {
return (
<div className="container">
<p>Code Highlighting using PrismJS on Next.JS</p>
</div>
)
}
Then, we need to contain that code inside <``pre``> and <``code``> tags. The code will now be:
<pre><code class="language-jsx">export default function Posts(props) {
return (
&lt;div className=&quot;container&quot;&gt;
&lt;p&gt;Code Highlighting using PrismJS on Next.JS&lt;/p&gt;
&lt;/div&gt;
)
}</code></pre>
Lastly, we will highlight the code. use this command:
useEffect(() => {
Prism.highlightAll()
}, [])
Conclusion
There are some other methods like using babel, which is I personally use. But for starters, the way discussed in this blog post is more appropriate.