I've been trying to generate a snippet of code on my website on a rendered text editor using react-syntax-highlighter. I've spent a while using this plugin and love it, however I've come across an issue I can't find an answer to. I want to change some of the colors of the generated code but cannot find any other way to do this other than using their default selection of themes. They allow you to apply styles to the background and the code but not the spans that hold the colors, is there any simple way to create and apply a custom theme, or to simply target the specific classes and change their colors?
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { atomDark } from "react-syntax-highlighter/dist/esm/styles/prism";
const CodeDisplay = ({ active }) => {
const templateString = `
const NewObject = New Shop(
console.log('shop');
)
`
return (
<>
<SyntaxHighlighter
language="jsx"
style={atomDark}
wrapLongLines
customStyle={{
backgroundColor: "transparent",
opacity: "1",
marginTop: "-2rem",
}}
codeTagProps={{
style: {
color: "white",
},
}}>
{templateString}
</SyntaxHighlighter>
</>
);
};
The way that worked best for me in order to style the code similar to the
dark+
theme in Visual Studio Code is to specifyuseInlineStyles={false}
to prevent react-syntax-highlighter (RSH) to add inline css style information to each span element produced. RSH however will specify a certain class name to that object that furthermore allows you to define your own CSS styles.My configuration i.e. looks like this:
this will produce an output like visible in the snippet added at the bottom of this post.
The lexer
react-syntax-highlighter
uses has clearly some issues as in case of multi-line comments a new line start indicated by a new line number is annotated here with aclass="hljs-comment"
when it clearly shouldn't. Also, there are multiple things that aren't recognized and therefore tagged properly and thus a code highlighting like in your editor of choice might not be doable.With a CSS file also added as snippet below that basically defines the colors VSCode uses for certain key elements I obtain an output like in the right part of the picture below. For comparison purposes I also included the original styling of
dark+
style of VSCode for reference purposes. Some changes like the more greish-purple background are on purpose as it fits the theme of the page better.As further can be seen, the output RSH returns is not quite able to format the code like VSCode does though most of the colors should be similar to the one VSCode uses in that theme, at least a color picker did return these color values.
Line 19-21 in the image to the right showcases the line highlighting via the respective function used in the
lineProps
property, just in case if anybody wonders why they have a different color.