Categories
React Answers

How to highlight text using React?

Spread the love

Sometimes, we want to highlight text using React.

In this article, we’ll look at how to highlight text using React.

How to highlight text using React?

To highlight text using React, we can create our own component where we check whether each word matches what we want to highlight.

For instance, we write:

import React from "react";

const Highlighted = ({ text = "", highlight = "" }) => {
  if (!highlight.trim()) {
    return <span>{text}</span>;
  }
  const regex = new RegExp(`(${highlight})`, "gi");
  const parts = text.split(regex);

  return (
    <span>
      {parts.filter(String).map((part, i) => {
        return regex.test(part) ? (
          <mark key={i}>{part}</mark>
        ) : (
          <span key={i}>{part}</span>
        );
      })}
    </span>
  );
};

export default function App() {
  return (
    <Highlighted
      text="the quick brown fox jumps over the lazy dog"
      highlight="fox"
    />
  );
}

to create the Highlighted component to highlight the text set as the highlight option.

To do the highlight, we create a regex that takes the highlight text and put it in parentheses so that they’ll be kept when we split the text with split.

We set the flags to 'gi' to look globally for matches in a case insensitive manner for the highlight.

Then we call text.split with regex to split the text.

Next, we render a span and we check for each part entry in parts.

If the part matches the regex as we check with regex.test, when we render it in a mark element to highlight it.

Otherwise, we render it in a span.

As a result, we should see the word ‘fox’ highlighted in the sentence.

Conclusion

To highlight text using React, we can create our own component where we check whether each word matches what we want to highlight.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

5 replies on “How to highlight text using React?”

I like the simplicity of this example but it contains 2 errors.
1) Regex should be escaped. Try to highlight “(a)”.
2) “g” flag gives wrong result when you try to highlight “a” in “aaaaaa” due to lastIndex.

Good Input, I worked in your feedback, now it should work also with the two mentioned errors:

const escapeRegExp = (text) => text.replace(/[-[]{}()*+?.,\^$|#\s]/g, ‘\$&’);
const regex = new RegExp((${escapeRegExp(highlight)}), ‘i’);

if the highlight text is not one word, instead is an array of words, and need to be highlight in different colors. How to adjust the code to do it?

Instead of Tobias answer, below regex escape worked for me.

const escapeRegExp = function (str) {
return str.replace(/([.?*+^$[]\(){}|-])/g, ‘\$1’);
};

const regex = new RegExp((${highlight}), “gi”);
The above line is not working for “123\” text, getting below error-

SyntaxError: Invalid regular expression: /(123)/gi: Unterminated group

Leave a Reply

Your email address will not be published. Required fields are marked *