Create easily a text highlighter component in few lines of code using React

Romullo Bernardo
2 min readJan 11, 2022

--

When I had to use a text highlighter in React I couldn't really find any tutorial besides using libraries, or over-engineered solutions making use of things like dangerouslySetInnerHTML. There's really no need for that so I decided to share my simple solution.

Here's the code:

Now let's get to the explanations.

First, the component just receives a text, a search param and a caseSensitive boolean.

At line 2 we create a regex containing the search param we'll input. We also specify if we want it to be case sensitive or not.

At line 3 we use the match method to retrieve all matched expressions from the text.

At line 4 we use the split method so we can get all the remaining text that was not matched.

At line 5 is where the magic happens. We're going to use a reduce method so we can combine all the matched and non matched parts into a single array. If you're not familiarized with it, the first param is an accumulator, the second param is the current value, and the third param is an index. So we just have to create an array where we first get a non matched part, and then a matched part consecutively. We wrap the matched part in a <mark> tag in order to highlight it, and then repeat the process until it's over.

Finally we return the array, ready to be rendered.

We are done!!

Congratulations, you’ve just created a cool text highlighter component.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response