Search code examples
javascriptreactjsnext.jssyntax-highlighting

react-highlightjs not highlighting syntax code as expected


I am using react-highlight to highlight code in my next.js app, but I am getting the following code highlight while using the a11y-dark theme

getting

But on official website of highlightjs.org. They have given following highlight using the same theme(a11y-dark)

expected

There is a huge difference between both. I am not able to get where this difference is coming from.

I also imported stylesheets correctly. My next.js code is as follows. Can anyone tell how to fix this. Thanks!

'use client'
import styles from './Code.module.css'
import Highlight from 'react-highlight' 
import '../../node_modules/highlight.js/styles/a11y-dark.css'

export const Code = (props)=>{


    return<>
    <section className={styles.code}>
        <div className={styles.type}>
            Type:
            <select name="type" className={styles.type_select}>
                <option value="vjs">Vanilla Javascript</option>
                <option value="rjs">ReactJS / NextJS</option>
            </select>
        </div>
        <div className={styles.main_code}>
            <Highlight language="javascript">{props.code}</Highlight>
            
        </div>
    </section>
    </>
}

Solution

  • I'm not sure what the issue with react-highlight is but there's a separate package that will give you what you want: react-syntax-highlighter

    Full code here:

    import React from 'react';
    import SyntaxHighlighter from 'react-syntax-highlighter';
    import { a11yDark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
    
    const CodeBlock: React.FC<{ codestring: string }> = ({ codestring }) => {
      return (
        <SyntaxHighlighter
          language="javascript"
          style={a11yDark}
          showLineNumbers>
          {codestring}
        </SyntaxHighlighter>
      );
    };
    
    function App() {
    
      var code = `function $initHighlight(block, cls) {
        try {
          if (cls.search(/\bno\-highlight\b/) != -1)
            return process(block, true, 0x0F) +
                   \` class="\${cls}"\`;  
        } catch (e) {
          /* handle exception */
        }
        for (var i = 0 / 2; i < classes.length; i++) {
          if (checkCondition(classes[i]) === undefined)
              return /\d+[\s/]/g;
          }
           return 0xA;
        }
        
        export  $initHighlight;`;
    
      return (
        <div className="w-1/2 bg-blue-700">
          <CodeBlock codestring={code} />
        </div>
      );
    }
    
    export default App;
    

    I tested the a11yDark style and it matches your second screenshot: enter image description here