What is prism-react-renderer?
The prism-react-renderer package is a React component that leverages PrismJS, a syntax highlighter written in JavaScript, to render syntax-highlighted code in React applications. It is highly customizable and can be used to implement code highlighting with various themes and styles directly in React projects.
Syntax Highlighting
This feature allows developers to easily implement syntax highlighting in their React applications. The code sample demonstrates how to use prism-react-renderer to highlight JavaScript code with the 'darcula' theme.
import React from 'react';
import { render } from 'react-dom';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { darcula } from 'react-syntax-highlighter/dist/esm/styles/prism';
const Component = () => {
const codeString = '(num) => num + 1';
return (
<SyntaxHighlighter language='javascript' style={darcula}>
{codeString}
</SyntaxHighlighter>
);
};
render(<Component />, document.getElementById('root'));
Custom Theming
This feature demonstrates how to apply a custom theme (in this case, 'nightOwl') to the code highlighting. It shows the flexibility of prism-react-renderer in terms of theming and customization.
import React from 'react';
import Highlight, { defaultProps } from 'prism-react-renderer';
import theme from 'prism-react-renderer/themes/nightOwl';
const exampleCode = `function add(a, b) {
return a + b;
}`;
const Component = () => (
<Highlight {...defaultProps} theme={theme} code={exampleCode} language='javascript'>
{({ className, style, tokens, getLineProps, getTokenProps }) => (
<pre className={className} style={style}>
{tokens.map((line, i) => (
<div {...getLineProps({ line, key: i })}>
{line.map((token, key) => (
<span {...getTokenProps({ token, key })} />
))}
</div>
))}
</pre>
)}
</Highlight>
);
export default Component;