One of the key features of a programming blog is code blocks.
It can also improve your codes readability.
This article will show you how to use react-syntax-highlighter to highlight code blocks in React.
Syntax Highlighting With react-syntax-highlighter
The react syntax highlighter allows you to highlight code using React.
That approach is dangerous because it exposes an system tocross-site scripting attacks.
Instead, it uses a syntax tree to build the virtual DOM and updates it only with changes.
The component uses PrismJS and Highlight.js in the background.
you’re able to choose to use either to highlight your code.
It is very easy to use as it provides out-of-the-box styling.
The react-syntax-highlighter component accepts the code, language, and style as props.
The component accepts other customizing options as well.
you could find them in thereact syntax highlighter documentation.
Using the react-syntax-highlighter Component
To start using react syntax highlighter in React, install it via npm.
It also takes the code string as its contents.
The light build, however, does not have default styles.
You will also need to import and register the languages you want using theregisterLanguagefunction exported from the light build.
This component uses Highlight.js to highlight the code.
Using prism is beneficial, especially when highlighting jsx because react-syntax-highlighter does not fully support it.
With react-syntax-highlighter, you only need to passshowLineNumbersto the SyntaxHighlighter component and set it to true.
The component will now show line numbers next to your code.
The Importance of Syntax Highlighting
you could use the react-syntax-highlighter package to highlight code in React.