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


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.