loading

How to add highlight.js in react complete solution with sourcecode

Highlight js is a library to highlight the syntax of programming languages like HTML, CSS js, java,c, c++, etc. There is no proper documentation for react to implement highlight js.

npm i highlight.js

How to use highlight js in react component

After installing the package import highlight js and call in use effect hook as it will be applied on the code after the dom content is loaded. You can also override the CSS according to your own.

import "highlight.js/styles/github.css";
import hljs from "highlight.js";
import { useEffect } from "react";
const demo = () => {
  useEffect(() => {
    hljs.highlightAll();
  }, []);

  return (
    <>
      <code>
        <pre>
          <div class="main">
            <div class="post">
              <button class="readmore">read more</button>
              <button>read more1</button>
              <button>read more2</button>
              <button>read more3</button>
            </div>
          </div>
        </pre>
      </code>
    </>
  );
};

export default demo;

by default, highlight js selects <code> tag to highlight but you can configure your own element also to highlight code if you are placing the code in any other tag instead of the code tag.

We strongly recommend¬†<pre><code>¬†wrapping for code blocks. It’s quite semantic and “just works” out of the box with zero fiddling

highlight js

How to ignore code block to highlight

You can use nohighlight class to ignore the code block to highlight.

<pre><code class="nohighlight">...</code></pre>

Highlighting code with specific language

To highlight code with a specific language, use highlight in the following way

html = hljs.highlight('<h1>Hello World!</h1>', {language: 'xml'}).value

Highlighting code after dom content load

To initiate highlight.js after dom content loads call it after the dom content loaded event

document.addEventListener('DOMContentLoaded', (event) => {
  document.querySelectorAll('pre code').forEach((el) => {
    hljs.highlightElement(el);
  });
});

To highlight custom code blocks manually:

// first, find all the div.code blocks
document.querySelectorAll('div.code').forEach(el => {
  // then highlight each
  hljs.highlightElement(el);
});

check more demos here

About Author

x

Order for website design

Help :