Replace text adding element and styles in react dynamically

I have a block of text that is coming from the database and it’s being mapped into a <p> element in react. During the mapping process that string is being run through a function that adds a strong tag around text if it matches what is input into a filter. For example if the string is “hello my name is fred” and the user inputs fred into the search, a <strong> tag will be wrapped around fred to make it stand out. What I’d like to do is add additional styles and not just use a strong tag but I can’t figure out how to do that w/ the restrictions of react. Here is my current code being used to dynamically add the strong tag →

inputText.forEach((item) => {
    const substring = new RegExp(item, "gi");
    result = result.replace(substring, (highlight) => `<strong>${highlight}</strong>`);

the issue is if I try to change the strong to a div and add either a style attribute or classname to it, it doesn’t seem to be rendered correctly by the dom using whatever styles I add. I’m not entirely sure how to solve this issue in react. Thanks!

Can we see what you’ve tried?

I’ve basically tried some combos of

result.replace(substring, (highlight) => `<div style={{backgroundColor: "yellow"}}>${highlight}</div>`);
result.replace(substring, (highlight) => `<div className={classes.test}>${highlight}</div>`);
result.replace(substring, (highlight) => `<div style="backgroundColor: yellow">${highlight}</div>`);
result.replace(substring, (highlight) => <div style={{backgroundColor: "yellow"}}>`${highlight}`</div>);

It’s not clear what your setup is, how this is all connecting up. But I notice that your function returns a string, not JSX:

result = result.replace(substring, (highlight) => `<strong>${highlight}</strong>`);

Because of that, you may have to use standard HTML notation instead of JSX.

You might try:

result.replace(substring, (highlight) => `<div class={classes.test}>${highlight}</div>`);


result.replace(substring, (highlight) => `<div style="background-color: yellow">${highlight}</div>`);

@kevinSmith Thank you so much!! The problem was in fact that I was mixing JSX syntax and doing

result.replace(substring, (highlight) => `<div style="background-color: yellow">${highlight}</div>`);

works great!! I appreciate your help, I was pulling my hair out on this one.

1 Like

Trust me, we’ve all been there…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.