Enhancing your website content with syntax highlighting is a crucial factor in retaining readers on your site. This practice can significantly reduce the bounce rate, ultimately improving your website's ranking. Has this idea crossed your mind?
An easily scannable and navigable source code also plays a vital role in guiding readers to focus on specific parts of an article to solve their problems.
This quick and easy syntax highlighter tutorial can assist you in presenting a beautiful source code within your website content.
Installing react-syntax-highlighter
To add syntax highlighting to your React application, you can use the
react-syntax-highlighter
package.These commands below show you how to install the package in your project. Select the command based on your package manager of choice.
# NPM npm install react-syntax-highlighter # YARN yarn add react-syntax-highlighter # PNPM pnpm install react-syntax-highlighter
Basic Syntax Highlighting Usage with react-syntax-highlighter
In this section, you will learn how to use syntax highlighting using the
react-syntax-highlighter
library in its basic form.Suppose you have the following code that you want to display with syntax highlighting, this code is a Javascript code.
const sourceCode = "console.log('Hello, world!');";
To render the source code with syntax highlighting using the
react-syntax-highlighter
library, follow these steps:- Import the
SyntaxHighlighter
component from the library.
- Import the desired style from the
react-syntax-highlighter
styles.
- Use the
SyntaxHighlighter
component.
- Pass the
language
prop to specify the programming language of the source code.
- Pass the
style
prop to select the visual theme for highlighting.
- Pass the source code as the children of the
SyntaxHighlighter
component.
Here's an example of these steps in action:
// Step 1 import { SyntaxHighlighter } from 'react-syntax-highlighter'; // Step 2 import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs'; {/* Steps 3 and 4 */} <SyntaxHighlighter language="javascript" style={docco}> {sourceCode} {/* Step 6 */} </SyntaxHighlighter>
In the example above,
docco
is a predefined style from the react-syntax-highlighter
library. You can choose from a variety of available styles to match your preferences.Available Props in SyntaxHighlighter
When using the
SyntaxHighlighter
component from the react-syntax-highlighter
library, you can customize the behavior and appearance of the syntax highlighting using various props. Here are the available props and their descriptions:
language
Specifies the language to highlight code in. Available options for hljs or prism. Pass
'text'
to render plain monospaced text.Using this prop, you can highlight different source code from many programming languages.
<SyntaxHighlighter language="javascript" style={docco}> {sourceCode} </SyntaxHighlighter>
style
Defines the visual style for the syntax highlighting. Import styles from
styles/hljs
or styles/prism
based on your import path.Styling with custom style helps in providing good experience to the reader when they have different code highlighting preference.
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs'; <SyntaxHighlighter language="javascript" style={docco}> {sourceCode} </SyntaxHighlighter>
wrapLines
Controls whether lines of code should be wrapped in a parent element.
You can force wrap line so reader don’t need to scroll horizontally to see all code. Or you can disable wrapping to display source code as it is.
<SyntaxHighlighter wrapLines={true} language="javascript" style={docco}> {sourceCode} </SyntaxHighlighter>
showLineNumbers
Displays line numbers next to the code block.
This is particularly useful when you mention the line number in your content. Reader can easily jump to the line number instead of skimming through the source code again.
<SyntaxHighlighter showLineNumbers={true} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
showInlineLineNumbers
Renders line numbers into each line, suitable for specific renderers like
react-syntax-highlighter-virtualized-renderer
.<SyntaxHighlighter showLineNumbers={true} showInlineLineNumbers={true} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
startingLineNumber
Specifies the starting line number for line numbering. This is useful when you need to show specific code snippet.
For example you are a developer tasked to create a website that shows code review. You can select specific code to be displayed to the user.
<SyntaxHighlighter showLineNumbers={true} startingLineNumber={5} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
wrapLongLines
Controls how long lines of code are displayed.
<SyntaxHighlighter wrapLongLines={true} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
lineNumberContainerStyle
Overrides styling for the line numbers container.
If you need to create an overlapping line number like in a code diffing tool, you can use custom style for to differentiate between code versions.
<SyntaxHighlighter lineNumberContainerStyle={{ paddingLeft: '20px' }} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
lineNumberStyle
Applies styles to each line number.
One of use case is to differentiate between removed code, added code, and updated code if you are working on a code diffing app.
<SyntaxHighlighter lineNumberStyle={(lineNumber) => ({ color: lineNumber % 2 === 0 ? 'red' : 'blue' })} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
customStyle
Adds custom styles to the top-level
<pre>
tag.<SyntaxHighlighter customStyle={{ backgroundColor: 'lightgray' }} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
codeTagProps
Props to be applied to the
<code>
tag.<SyntaxHighlighter codeTagProps={{ className: 'custom-code' }} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
renderer
Allows custom rendering of lines of code.
<SyntaxHighlighter renderer={(props, ...children) => <span {...props}>{children}</span>} language="javascript" style={docco} > {sourceCode} </SyntaxHighlighter>
Showing Different Languages
This section demonstrates how the syntax highlighter works with different programming languages. Each programming language has its own set of tokens that need to be highlighted. The syntax highlighter automatically styles these tokens based on the
language
prop.Below snippets perfectly demonstrate how
SyntaxHighlighter
works when you pass a Typescript, Python, and PHP source code.TypeScript
In this Typescript code, the token that should be highlighted because it is a reserved keyword are
function
, string
, and return
. The other token comes from built-in functions, library, or user source code.import { SyntaxHighlighter } from 'react-syntax-highlighter'; import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs'; const typescriptCode = ` function greet(name: string): string { return 'Hello, ' + name; } console.log(greet('Alice')); `; <SyntaxHighlighter language="typescript" style={docco}> {typescriptCode} </SyntaxHighlighter>
Python
Some tokens that need to be highlighted in this Python source code are
def
and return
. import { SyntaxHighlighter } from 'react-syntax-highlighter'; import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs'; const pythonCode = ` def greet(name): return 'Hello, ' + name print(greet('Alice')) `; <SyntaxHighlighter language="python" style={docco}> {pythonCode} </SyntaxHighlighter>
PHP
Some tokens that need to be highlighted in this PHP source code are
function
and return
. import { SyntaxHighlighter } from 'react-syntax-highlighter'; import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs'; const phpCode = ` function greet($name) { return 'Hello, ' . $name; } echo greet('Alice'); `; <SyntaxHighlighter language="php" style={docco}> {phpCode} </SyntaxHighlighter>
Using Different Styles
In the above code examples, the
hljs
style was used to highlight the code. However, there are various styles available within hljs
that you can experiment with. Here are a few distinct styles you can try:Darcula
To use the
darcula
style for your code highlighting, simply import it from the react-syntax-highlighter/dist/esm/styles/hljs
directory and apply it as the style
prop:import { SyntaxHighlighter } from 'react-syntax-highlighter'; import { darcula } from 'react-syntax-highlighter/dist/esm/styles/hljs'; <SyntaxHighlighter language="typescript" style={darcula}> {typescriptCode} </SyntaxHighlighter>
Solarized Light
import { SyntaxHighlighter } from 'react-syntax-highlighter'; import { solarizedlight } from 'react-syntax-highlighter/dist/esm/styles/hljs'; <SyntaxHighlighter language="typescript" style={solarizedlight}> {typescriptCode} </SyntaxHighlighter>
Atom One Light
import { SyntaxHighlighter } from 'react-syntax-highlighter'; import { atomOneLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'; <SyntaxHighlighter language="typescript" style={atomOneLight}> {typescriptCode} </SyntaxHighlighter>
Conclusion
Using
SyntaxHighlighter
can bring much more opportunity when you need to display source code to the reader.The available props allows you to customize the behavior of
SyntaxHighlighter
that fits different scenario for your use case.You can use it to show different language highlighting or utilize different styles from
hljs
library.Happy highligting!