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.