Syntax Highlighting with CKEditor's Code Block
Adam C. |

CKEditor 5 does not ship with Code Blocks by default, but it could be added via custom build. The simplest way to use it is from ckeditor5-build-classic-dna. However, it does not support Syntax Highlighting. The good thing is that it's fairly easy to add one via the front-end library.

Although live code block highlighting is impossible when editing in CKEditor 5 (learn more), the content can be highlighted when displayed in the frontend (e.g. in blog posts, messages, etc.).

Here we will show you how to do this in React Component with prismjs.

Step 1

Install prismjs NPM.

npm install -i prismjs

Step 2

Import CSS, for NextJS, we can import it in _app.js, like

import "prismjs/themes/prism.css";

Step 3

The CKEditor's Code Block plugin generates the standard code format, which works with prismjs without any change, the code snippet is like this:

	<code class="language-javascript">
		window.alert( 'Hello world!' )

And we just need to call the prismjs' function highlightAll after the component is mounted: either in ComponentDidMount React Lifecycle or use useEffect, like below:

const Post = (props) => {
  //skip some code here ...
  useEffect(() => {
  }, [content]);

  return (
    <Layout seoData={seoData}>
      <Container text>
        <Header as="h1">
            {author} | <TimeAgo date={publishedOn} />

        <div dangerouslySetInnerHTML={{ __html: content }} />

Step 4

No more, that's it! 

Final Note:

In case, you don't like the default theme (prism.css), you can import different theme at step 2, here is the list of options: