Search code examples
reactjshighlightjs

ReactJS highlight blog post that comes from the server


I've been trying to use highlight.js with my react project , but it never worked. I have a blog, and for each post I fetch the post data from the server. Unfortunately - highlight.js does not work properly when it comes to dynamic data and async proccess. Lets say we have this code that i fetch:

bla blba blahbla blba blahbla blba blahbla blba blah...
<code><div class="test"></div></code>
bbla blba blah....

So , I did try to import highlight.js with the css theme, and used hljs.highlightAll() , but it didn't work properly. Maybe there is some other solution \ library where I can highlight the code? What's the alternative? thank you.

import { React, useEffect } from "react";
import { useParams } from "react-router-dom";
import hljs from "../../node_modules/highlight.js/lib/core";
import "../../node_modules/highlight.js/styles/arta.css";
import "./BlogPost.css";

function BlogPost(props) {
  hljs.initHighlightingOnLoad();

  const updateCodeSyntaxHighlighting = () => {
    document.querySelectorAll("code").forEach((block) => {
      hljs.highlightBlock(block);
    });
  };
  useEffect(() => {
    getPostData();
    updateCodeSyntaxHighlighting();
  }, []);

  // GetPostDataById(id);
  return <div dangerouslySetInnerHTML={{ __html: postData }}></div>;
}

export default BlogPost;

result: enter image description here

as you can see - the background gets darker , but not really highlighted text.


Solution

  • Your not importing the entire highlight.js library so you can just do import hljs from 'highlight.js' instead of going into the node modules folder to get it. Also you are not specifying the language you want to highlight in with the class of the code block. In the example I am just going to hard code the postData with class='language-javascript' for the <code> block to get the correct syntax highlighting. So here is a working example:

    Working Codesandbox

    import { React, useEffect } from 'react'
    import hljs from 'highlight.js'
    import '../../node_modules/highlight.js/styles/arta.css'
    
    const postData = `<pre><code class="language-javascript">console.log('hello');</code></pre>`
    
    function BlogPost(props) {
      const updateCodeSyntaxHighlighting = () => {
        document.querySelectorAll('code').forEach((block) => {
          hljs.highlightElement(block)
        })
      }
    
      useEffect(() => {
        updateCodeSyntaxHighlighting()
      }, [])
    
      // GetPostDataById(id);
      return <div dangerouslySetInnerHTML={{ __html: postData }}></div>
    }