How to highlight a word on mouseover in text in a React app
const text = data[data.length - 1] !== undefined ? data[data.length - 1].taskText : null;
const [hilightWord, setHilightWord] = useState(false);
const hightlight = (text, hilightWord) => {
if (!hilightWord) return text;
const regex = new RegExp(`(${hilightWord})`, "gi");
return text.split(regex).map((substring, i) => {
return (
<span className={styles.highlight} key={i}>
{substring}
</span>
);
});
};
<p className={styles.text} onMouseMove={() => setHilightWord(true)} onMouseLeave={() => setHilightWord(false)}>{hightlight(text, hilightWord)}</p>
3
Answers
Not sure if this is exactly your requirement, but it seems like you want the text to be highlighted on
mouseover
. A really easy way to achieve this is by using CSS:hover
selector (this wont even require any JavaScript).Implementation:
CSS:
In your styles variable add this.
You could
spit()
your sentence, then wrap it in some DOM element (em
for example), then you can use some CSS to set a:hover
color on the words.Small example: