csssyntax-highlightingsyntaxhighlighter

How to use SyntaxHighlighter for inline code


I am using Syntax Highlighter for my website.But how can I use it for inline code? I mean when I use it for inline code it still shows the line number 1 and I want to remove it as it makes no sense to show line number for inline code

i.e

I want

"This is a java print code System.out.println("Hello");"

instead of

"This is a java print code 1 |System.out.println("Hello");"

(notice the line number in second case)

I searched it on google but no success.


Solution

  • You will have to use a custom code block and style it yourself to achieve it:

    Algo:

    1. If Inline Display Custom Block
    2. Else Allow SyntaxHighlighter to do its magic.

    I have used the below code:

    CodeHighlighter.js

    import {Prism as SyntaxHighlighter} from "react-syntax-highlighter";
    import {dracula} from "react-syntax-highlighter/dist/esm/styles/prism";
    import './CodeHighlighter.css'
    import {Card} from "@mui/material";
    
    function cleanChildren(children){
        for (var i = 0; i < children.length; i++){
            children[i] = children[i].trim()
        }
        return children
    }
    
    export default function CodeHighlight({node, inline, className, children, ...props}) {
        var lang = "";
        try {
            lang = className.replace("language-", "");
        } catch {
            lang = "";
        }
    
        return (
            <div className='highlightRoot'>
                {inline ?
                    (
                        <Card className='inlineCode' variant='outlined'>
                            <code >{children}</code>
                        </Card>
                    )
                    : (
                        <div>
                            <SyntaxHighlighter
                                language={lang}
                                style={dracula}
                                showLineNumbers={!inline}
                                startingLineNumber={1}
                                children={cleanChildren(children)}
                            />
                            <p>{lang}</p>
                        </div>
                    )
                }
            </div>
    
        );
    }
    

    CodeHighlighter.css

    .highlightRoot{
        display: inline;
    }
    
    .inlineCode{
        display: inline;
        padding: 0 4px;
        background-color: #4b4b59;
        color: white;
    }
    

    I have been using this in conjunction with ReactMarkdown library.

    What I was able to achieve:

    SyntaxHighlighter Inline Code