Is it possible to highlight specific characters in a line using react-syntax-highlighter?

908 Views Asked by At

I created the following React component. It implements react-syntax-highlighter:

import React from "react";
import { PrismAsyncLight as SyntaxHighlighter } from "react-syntax-highlighter";
import { coy } from "react-syntax-highlighter/dist/cjs/styles/prism";

export type CodeViewerProps = {
    language: string;
    code: string;
    linesToHighlight?: number[];
    startingLineNumber?: number;
}

export function CodeViewer({
    language, code, linesToHighlight = [], startingLineNumber = 1,
}: CodeViewerProps) {
    return (
        <SyntaxHighlighter
            startingLineNumber={startingLineNumber}
            language={language}
            style={coy}
            showLineNumbers
            wrapLines
            lineProps={(lineNumber) => {
                const style = { display: "block", width: "fit-content" };
                if (linesToHighlight.includes(lineNumber)) {
                    style.backgroundColor = "#ffe7a4";
                }
                return { style };
            }}
        >
            {code}
        </SyntaxHighlighter>
    );
}

As you can see, I use the lineProps prop to highlight a specific line by setting its background color. When I use the above component, it results in an output that looks like this:

react-syntax-highlighter React.js example

In the highlighted line above, you can see the string "SUPER_SECRET_TOKEN". I'd like to know if there is any way that I can apply a different background color just for that string. Is it possible to supply a start character and an end character to apply specific styles?

I've looked through the documentation and I didn't find anything that could help me highlight specific characters in a line. I attempted to write a custom script that parses the DOM structure of the syntax highlighter component but it turned out to be very unreliable.

0

There are 0 best solutions below