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:

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

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:

// github.com/deniapps/nextfeathers/blob/master/next/pages/blog/%5Bslug%5D.js
const Post = (props) => {
  //skip some code here ...
  useEffect(() => {
    Prism.highlightAll();
  }, [content]);

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

        <div dangerouslySetInnerHTML={{ __html: content }} />
      </Container>
    </Layout>
  );
};

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:

https://github.com/PrismJS/prism-themes/tree/master/themes