Syntax highlighting is a feature that displays source code or markup in different colors and fonts according to the category of terms. This makes the code more readable and helps developers understand the structure and logic. In the context of web applications, particularly those built with React, syntax highlighting can significantly enhance the user experience for those interacting with code snippets.
Highlight.js is a popular library that offers syntax highlighting for web applications. It is lightweight, easy to use, and supports many programming languages. In this blog, we will explore how to integrate Highlight.js into a React application to provide syntax highlighting and specified element syntax highlighting and improve the readability of code snippets.
Highlight.js is a JavaScript library that provides syntax highlighting for text formats like HTML, JSON, or any other string format that requires syntax highlighting. It automatically detects the language in the code snippet and applies corresponding styles to highlight the syntax. This is particularly useful in React applications where you might need to render code snippet inside a component.
The library is not only about aesthetics; it also helps debugging and code review by making it easier to spot errors or key elements in the code. Incorporating Highlight.js into your React project can enhance the overall development experience and provide a more engaging interface for users interacting with code snippets.
To start with Highlight.js in your React project, you must first install the library. You can do this using npm with the following command:
1npm install highlight.js --save
Once installed, you can import Highlight.js into your React component to highlight code snippets. You will also need to import the styles for the syntax highlighting, which can be done by including the CSS file for the desired theme in your project.
Here's a simple example of how to set up Highlight.js in a React component:
1import React from 'react'; 2import hljs from 'highlight.js'; 3import 'highlight.js/styles/default.css'; // Import the default Highlight.js style 4 5class CodeBlock extends React.Component { 6 componentDidMount() { 7 this.highlightCode(); 8 } 9 10 componentDidUpdate() { 11 this.highlightCode(); 12 } 13 14 highlightCode() { 15 const nodes = document.querySelectorAll('pre code'); 16 nodes.forEach(node => hljs.highlightBlock(node)); 17 } 18 19 render() { 20 return ( 21 <pre> 22 <code> 23 {this.props.value} 24 </code> 25 </pre> 26 ); 27 } 28} 29
In the above example, the highlightCode method is called after the component mounts and updates, which applies Highlight.js to each pre code block within the component.
When you want to render code snippet inside a React component with Highlight.js, you must ensure the library knows when to apply the syntax highlighting. This is typically done in the componentDidMount and componentDidUpdate lifecycle methods, as shown in the previous example. The highlightCode function iterates over all the DOM nodes that match the pre code selector and applies the Highlight.js highlighting.
Here's an example of how you might use Highlight.js to highlight a specific piece of code:
1render() { 2 const codeString = '(num) => num + 1'; 3 return ( 4 <pre> 5 <code> 6 {codeString} 7 </code> 8 </pre> 9 ); 10} 11
After the component mounts, Highlight.js will automatically detect the language of the code snippet and apply the corresponding styles to highlight the syntax.
Highlight.js comes with various themes that you can use to customize the appearance of your code snippets. To change the highlight color or theme, you must import the CSS file for the theme you want. You can also create a custom class name in inner HTML to apply additional styles or override the default styles provided by Highlight.js.
For example, to switch to a light mode theme, you might import a different CSS file:
1import 'highlight.js/styles/github.css'; // Import a light mode Highlight.js style 2
And to apply a custom class name for additional styling:
1render() { 2 return ( 3 <pre className="my-custom-class"> 4 <code> 5 {this.props.value} 6 </code> 7 </pre> 8 ); 9} 10
Then, in your CSS file, you can define the styles for .my-custom-class to customize the appearance of your code blocks.
You can render each in its pre-code block to highlight multiple code snippets within a single React component. Highlight.js will process each block independently, applying the necessary syntax highlighting.
Here's an example of how to render multiple code snippets:
1render() { 2 const firstSnippet = 'const x = 5;'; 3 const secondSnippet = 'const y = 10;'; 4 return ( 5 <div> 6 <pre><code>{firstSnippet}</code></pre> 7 <pre><code>{secondSnippet}</code></pre> 8 </div> 9 ); 10} 11
Each code snippet is wrapped in its own pre code block, allowing Highlight.js to highlight them separately.
When considering tools for implementing syntax highlighting in React, developers often compare Highlight.js with CodeMirror. While both libraries serve the purpose of syntax highlighting, they have different use cases and features.
Highlight.js primarily focuses on statically highlighting syntax for displayed but not edited code. It's lightweight and easy to integrate, making it a popular choice for blogs, documentation, and read-only code examples.
CodeMirror, on the other hand, is a text editor implemented in JavaScript for the browser. It is feature-rich and can create editable code blocks with syntax highlighting, line numbers, and other text editor features. CodeMirror is more suitable for interactive coding environments like online IDEs or live code editors.
The main differences lie in their functionality:
Highlight.js has built-in support for many languages and themes, but sometimes, you may need to highlight syntax for additional languages or create a custom theme. To add support for other languages, you can include the language definitions provided by Highlight.js and register them as needed.
Here's how you can add additional language support:
1import hljs from 'highlight.js'; 2import javascript from 'highlight.js/lib/languages/javascript'; 3import python from 'highlight.js/lib/languages/python'; 4 5hljs.registerLanguage('javascript', javascript); 6hljs.registerLanguage('python', python); 7
You can either use one of the many themes that come with Highlight.js or create your own by defining custom styles in your CSS file.
When using Highlight.js in React, there are several best practices to keep in mind to ensure optimal performance and security:
While Highlight.js is a solid choice for many developers, there are alternatives worth considering. Prism.js is another popular syntax highlighting library that is similar to Highlight.js but offers a different set of features and plugins. Another alternative is React Syntax Highlighter, a React component that wraps lowlight.js (a subset of Highlight.js) and provides syntax highlighting.
Each library has its strengths and trade-offs, so it's essential to evaluate them based on the specific needs of your project.
Incorporating Highlight.js into your React application can improve code snippets' readability and aesthetic appeal. With its ease of use, wide language support, and customizable themes, Highlight.js is an excellent choice for developers looking to highlight code in their React projects.
By following the best practices and considering the alternatives, you can choose the most appropriate syntax highlighting solution for your application, ensuring a better experience for developers and users.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.