react-syntax-highlighter vs react-highlight-words vs react-highlight
React Content Highlighting Strategies
react-syntax-highlighterreact-highlight-wordsreact-highlightSimilar Packages:

React Content Highlighting Strategies

react-highlight and react-syntax-highlighter are designed for code syntax highlighting, leveraging engines like Highlight.js or Prism to colorize programming languages. react-highlight-words serves a different purpose, focusing on highlighting specific search terms or phrases within plain text content. Selecting the right tool depends on whether your goal is to display code blocks with proper syntax coloring or to emphasize user search queries within paragraphs.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-syntax-highlighter4,570,6394,6732.19 MB13710 days agoMIT
react-highlight-words522,3152,30347.7 kB07 days agoMIT
react-highlight33,95976118.4 kB29-MIT

React Content Highlighting Strategies: Code vs. Text

When building React applications, you often need to highlight content for better readability. However, not all highlighting packages serve the same purpose. react-highlight and react-syntax-highlighter focus on code syntax, while react-highlight-words targets plain text search terms. Understanding these differences is critical for architectural decisions.

đŸŽ¯ Core Purpose: Code Syntax vs. Search Terms

The most important distinction lies in what each package is designed to highlight. Using a code highlighter for text search is inefficient, and using a text highlighter for code ignores syntax rules.

react-highlight is built for code syntax using Highlight.js.

  • It analyzes code strings and applies classes based on language grammar.
  • Best for displaying snippets in blogs or documentation.
// react-highlight: Code syntax
import Highlight from 'react-highlight';

function CodeBlock() {
  return (
    <Highlight className="javascript">
      {`console.log("Hello World");`}
    </Highlight>
  );
}

react-syntax-highlighter is also for code syntax but supports multiple engines.

  • It allows switching between Prism and Highlight.js.
  • Offers more control over rendering and features.
// react-syntax-highlighter: Code syntax
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';

function CodeBlock() {
  return (
    <SyntaxHighlighter language="javascript">
      {`console.log("Hello World");`}
    </SyntaxHighlighter>
  );
}

react-highlight-words is built for plain text search terms.

  • It does not understand code syntax or languages.
  • It highlights specific substrings within a text block.
// react-highlight-words: Text search
import Highlighter from 'react-highlight-words';

function SearchResults() {
  return (
    <Highlighter
      searchWords={['Hello']}
      textToHighlight="Hello World"
    />
  );
}

🎨 Styling and Themes

How you apply styles varies significantly between code highlighters and text highlighters. Code highlighters often rely on pre-built themes, while text highlighters require custom CSS for match tags.

react-highlight uses Highlight.js themes via CSS imports.

  • You import a CSS file provided by the library.
  • Limited to available Highlight.js themes.
// react-highlight: Theme import
import 'highlight.js/styles/github.css';

// Usage automatically picks up the CSS
<Highlight className="javascript">{code}</Highlight>

react-syntax-highlighter supports dynamic theme switching.

  • You pass the theme as a prop.
  • Easier to allow users to toggle between light and dark modes.
// react-syntax-highlighter: Dynamic theme
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';

<SyntaxHighlighter language="javascript" style={docco}>
  {code}
</SyntaxHighlighter>

react-highlight-words requires custom CSS for highlights.

  • You define how the highlighted text looks using highlightStyle.
  • Gives full control over background, color, and padding.
// react-highlight-words: Custom style
<Highlighter
  searchWords={['term']}
  textToHighlight="Some text with term"
  highlightStyle={{ backgroundColor: 'yellow', color: 'black' }}
/>

âš™ī¸ Configuration and Features

Feature sets differ based on the complexity of the highlighting task. Code highlighters need language detection and line numbers, while text highlighters need case sensitivity controls.

react-highlight offers basic configuration.

  • Primarily relies on className for language detection.
  • Lacks built-in line numbers or custom token rendering.
// react-highlight: Basic config
<Highlight className="python">{code}</Highlight>
// No built-in prop for line numbers

react-syntax-highlighter provides advanced features.

  • Supports line numbers, starting line index, and custom renderers.
  • Allows fine-tuning of code block behavior.
// react-syntax-highlighter: Advanced config
<SyntaxHighlighter
  language="python"
  showLineNumbers={true}
  startingLineNumber={10}
>
  {code}
</SyntaxHighlighter>

react-highlight-words focuses on text matching options.

  • Controls case sensitivity and match boundaries.
  • Allows custom rendering of highlight tags.
// react-highlight-words: Match options
<Highlighter
  searchWords={['term']}
  textToHighlight="Term and term"
  caseSensitive={false}
  highlightTag="span"
/>

đŸ› ī¸ Customization and Extensibility

When default behavior isn't enough, each package offers different extension points. Code highlighters allow custom token styling, while text highlighters allow custom match components.

react-highlight has limited customization.

  • You must override CSS classes to change token colors.
  • Harder to inject custom components into the code flow.
// react-highlight: CSS override
/* In your CSS file */
.hljs-keyword {
  color: blue !important;
}

react-syntax-highlighter allows custom renderers.

  • You can replace default elements with custom components.
  • Useful for adding copy buttons or interactive elements.
// react-syntax-highlighter: Custom renderer
<SyntaxHighlighter
  language="javascript"
  customStyle={{ background: '#f0f0f0' }}
>
  {code}
</SyntaxHighlighter>

react-highlight-words allows custom highlight components.

  • You can pass a component to render matches.
  • Enables adding icons or tooltips to highlighted words.
// react-highlight-words: Custom component
<Highlighter
  searchWords={['term']}
  textToHighlight="text"
  highlightTag={({ children, ...rest }) => (
    <span {...rest} className="custom-highlight">{children}</span>
  )}
/>

📊 Summary: Key Differences

Featurereact-highlightreact-syntax-highlighterreact-highlight-words
Primary UseCode SyntaxCode SyntaxText Search Terms
EngineHighlight.jsPrism or Highlight.jsNone (String Matching)
ThemesCSS ImportProp-basedCustom Style Object
Line Numbers❌ No✅ Yes❌ N/A
Custom Tags❌ Limited✅ Yes✅ Yes

💡 Final Recommendation

react-highlight is suitable for simple projects where you just need to display code with minimal setup. It works well if you are already using Highlight.js elsewhere and want a quick React wrapper.

react-syntax-highlighter is the standard choice for modern React applications requiring code display. Its support for multiple engines, line numbers, and dynamic themes makes it the most flexible option for documentation and developer tools.

react-highlight-words is the only choice for highlighting search terms in plain text. Do not attempt to use code highlighters for this task, as they will not match substrings correctly. Use this for search result pages or content filters.

Final Thought: Always match the tool to the content type. Use code highlighters for code blocks and text highlighters for user-generated content or search results. Mixing them leads to poor performance and incorrect rendering.

How to Choose: react-syntax-highlighter vs react-highlight-words vs react-highlight

  • react-syntax-highlighter:

    Choose react-syntax-highlighter if you need robust code highlighting with support for multiple engines (Prism or Highlight.js), line numbers, and extensive theme customization. It is ideal for documentation sites, code editors, or any application requiring detailed control over code block presentation.

  • react-highlight-words:

    Choose react-highlight-words if your primary goal is to highlight search terms or specific phrases within plain text, such as in search result lists or document viewers. It is the only package in this group designed for text substring matching rather than code syntax analysis.

  • react-highlight:

    Choose react-highlight if you need a lightweight wrapper around Highlight.js for simple code blocks without complex configuration. It is suitable for projects that require basic syntax coloring with minimal setup and do not need advanced features like line numbers or custom theme switching.

README for react-syntax-highlighter

React Syntax Highlighter

Actions Status npm

Syntax highlighting component for React using the seriously super amazing lowlight and refractor by wooorm

Check out a small demo here and see the component in action highlighting the generated test code here.

For React Native you can use react-native-syntax-highlighter

Installation Methods

For npm:

First install react-syntax-highlighter package

npm install react-syntax-highlighter --save

then install type modules to prevent TypeScript or ESLint Errors (Recommended for TypeScript):

npm install --save-dev @types/react-syntax-highlighter

For pnpm:

First add react-syntax-highlighter package

pnpm add -D react-syntax-highlighter

then install type modules to prevent TypeScript or ESLint related errors (Recommended for TypeScript):

pnpm add -D @types/react-syntax-highlighter

Why This One?

There are other syntax highlighters for React out there so why use this one? The biggest reason is that all the others rely on triggering calls in componentDidMount and componentDidUpdate to highlight the code block and then insert it in the render function using dangerouslySetInnerHTML or just manually altering the DOM with native javascript. This utilizes a syntax tree to dynamically build the virtual dom which allows for updating only the changing DOM instead of completely overwriting it on any change, and because of this it also uses more idiomatic React and allows the use of pure function components brought into React as of 0.14.

Javascript Styles!

One of the biggest pain points for me trying to find a syntax highlighter for my own projects was the need to put a stylesheet tag on my page. I wanted to provide out of the box code styling with my modules without requiring awkward inclusion of another libs stylesheets. The styles in this module are all javascript based, and all styles supported by highlight.js have been ported!

I do realize that javascript styles are not for everyone, so you can optionally choose to use css based styles with classNames added to elements by setting the prop useInlineStyles to false (it defaults to true).

Use

props

  • language - the language to highlight code in. Available options here for hljs and here for prism. (pass text to just render plain monospaced text)
  • style - style object required from styles/hljs or styles/prism directory depending on whether or not you are importing from react-syntax-highlighter or react-syntax-highlighter/prism directory here for hljs. and here for prism. import { style } from 'react-syntax-highlighter/dist/esm/styles/{hljs|prism}' . Will use the default if the style is not included.
  • children - the code to highlight.
  • customStyle - prop that will be combined with the top level style on the pre tag, styles here will overwrite earlier styles.
  • codeTagProps - props that will be spread into the <code> tag that is the direct parent of the highlighted code elements. Useful for styling/assigning classNames.
  • useInlineStyles - if this prop is passed in as false, react syntax highlighter will not add style objects to elements, and will instead append classNames. You can then style the code block by using one of the CSS files provided by highlight.js.
  • showLineNumbers - if this is enabled line numbers will be shown next to the code block.
  • showInlineLineNumbers - if this is enabled in conjunction with showLineNumbers, line numbers will be rendered into each line, which allows line numbers to display properly when using renderers such as react-syntax-highlighter-virtualized-renderer. (This prop will have no effect if showLineNumbers is false.)
  • startingLineNumber - if showLineNumbers is enabled the line numbering will start from here.
  • lineNumberContainerStyle - the line numbers container defaults to appearing to the left with 10px of right padding. You can use this to override those styles.
  • lineNumberStyle - inline style to be passed to the span wrapping each number. Can be either an object or a function that receives the current line number as an argument and returns a style object.
  • wrapLines - a boolean value that determines whether or not each line of code should be wrapped in a parent element. defaults to false, when false one can not take action on an element on the line level. You can see an example of what this enables here
  • wrapLongLines - boolean to specify whether to style the <code> block with white-space: pre-wrap or white-space: pre. Demo
  • lineProps - props to be passed to the span wrapping each line if wrapLines is true. Can be either an object or a function that receives the current line number as an argument and returns a props object.
  • renderer - an optional custom renderer for rendering lines of code. See here for an example.
  • PreTag - the element or custom react component to use in place of the default pre tag, the outermost tag of the component (useful for a custom renderer not targeting the DOM).
  • CodeTag - the element or custom react component to use in place of the default code tag, the second tag of the component tree (useful for a custom renderer not targeting the DOM).
  • spread props pass arbitrary props to pre tag wrapping code.
import SyntaxHighlighter from 'react-syntax-highlighter';
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';
const Component = () => {
  const codeString = '(num) => num + 1';
  return (
    <SyntaxHighlighter language="javascript" style={docco}>
      {codeString}
    </SyntaxHighlighter>
  );
};

Prism

Using refractor we can use an ast built on languages from Prism.js instead of highlight.js. This is beneficial especially when highlighting jsx, a problem long unsolved by this module. The semantics of use are basically the same although a light mode is not yet supported (though it is coming in the future). You can see a demo(with jsx) using Prism(refractor) here.

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';
const Component = () => {
  const codeString = '(num) => num + 1';
  return (
    <SyntaxHighlighter language="javascript" style={dark}>
      {codeString}
    </SyntaxHighlighter>
  );
};

Light Build

React Syntax Highlighter used in the way described above can have a fairly large footprint. For those who desire more control over what exactly they need, there is an option to import a light build. If you choose to use this you will need to specifically import desired languages and register them using the registerLanguage export from the light build. There is also no default style provided.

import { Light as SyntaxHighlighter } from 'react-syntax-highlighter';
import js from 'react-syntax-highlighter/dist/esm/languages/hljs/javascript';
import docco from 'react-syntax-highlighter/dist/esm/styles/hljs/docco';

SyntaxHighlighter.registerLanguage('javascript', js);

You can require PrismLight from react-syntax-highlighter to use the prism light build instead of the standard light build.

import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';
import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx';
import prism from 'react-syntax-highlighter/dist/esm/styles/prism/prism';

SyntaxHighlighter.registerLanguage('jsx', jsx);

Async Build

For optimal bundle size for rendering ASAP, there's an async version of prism light & light. This version requires you to use a bundler that supports the dynamic import syntax, like webpack. This will defer loading of the refractor (17kb gzipped) & the languages, while code splits are loaded the code will show with line numbers but without highlighting.

Prism version:

import { PrismAsyncLight as SyntaxHighlighter } from 'react-syntax-highlighter';

Highlight version

import { LightAsync as SyntaxHighlighter } from 'react-syntax-highlighter';

Supported languages

Access via the supportedLanguages static field.

SyntaxHighlighter.supportedLanguages;

Add support for another language

To add another language, use the light build and registerLanguage. For example to add cURL with highlight.js:

import { Light as LightSyntaxHighlighter } from 'react-syntax-highlighter';
import curl from 'highlightjs-curl';

Then you can do:

LightSyntaxHighlighter.registerLanguage('curl', curl);

Built with React Syntax Highlighter

  • mdx-deck - MDX-based presentation decks
  • codecrumbs - Learn, design or document a codebase by putting breadcrumbs in source code. Live updates, multi-language support, and easy sharing.
  • Spectacle Editor - An Electron based app for creating, editing, saving, and publishing Spectacle presentations. With integrated Plotly support.
  • Superset - Superset is a data exploration platform designed to be visual, intuitive, and interactive.
  • Daydream - A chrome extension to record your actions into a nightmare script
  • CodeDoc - Electron based application built with React for creating project documentation
  • React Component Demo - A React Component to make live editable demos of other React Components.
  • Redux Test Recorder - a redux middleware to automatically generate tests for reducers through ui interaction. Syntax highlighter used by react plugin.
  • GitPoint - GitHub for iOS. Built with React Native. (built using react-native-syntax-highlighter)
  • Yoga Layout Playground - generate code for yoga layout in multiple languages
  • Kibana - browser-based analytics and search dashboard for Elasticsearch.
  • Golangci Web
  • Storybook Official Addons
  • Microsoft Fast DNA
  • Alibaba Ice
  • Uber BaseUI Docs
  • React Select Docs
  • Auto-layout - use flex layout
  • npmview - A web application to view npm package files
  • Static Forms - Free HTML forms for your static websites.
  • React DemoTab - A React component to easily create demos of other components
  • codeprinter - Print out code easily
  • Neumorphism - CSS code generator for Soft UI/Neumorphism shadows
  • grape-ui - Component library using styled-system and other open source components.
  • Good Arduino Code - A curated library of Arduino Coding examples
  • marmota.app - A desktop app to create simple markdown presentations
  • boemly - An open-source component library for React.
  • Markdown Sticky Notes - A web extension to create Markdown sticky notes in web pages.

If your project uses react-syntax-highlighter please send a pr to add!

License

MIT

Contributing

You'll need Node 16.x installed & active on your system to build this package.

npm i
npm run dev