How to Highlight Specific Lines in react-syntax-highlighter?
Here's a solution from StackOverflow:
Original: Is it possible to highlight specific characters in a line using react-syntax-highlighter?
Solution:
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>
);
}
The key code is:
lineProps={(lineNumber) => {
const style = { display: "block", width: "fit-content" };
if (linesToHighlight.includes(lineNumber)) {
style.backgroundColor = "#ffe7a4";
}
return { style };
}}