Mike
Mike

Reputation: 419

Replace in string from an array of modified strings

I'm trying to to take a string with [WORDS] within it and replace it with the contents of my array. Each item in the array should be wrapped <strong> elements.

For instance, I have this string.

let output = "This is my string body with [WORDS] within it.";

Now I have an array of words coming from an API endpoint and looks something like:

["test","word1","word2","word3"]

When the array comes in, I'm mapping it so that each array element can be wrapped in <strong>:

let words = api_words.map(function (word) {
  return `<strong>${word}</strong>`;
});

And then I pass my words to a replace function.

const formatted = string.replace("[WORDS]", words);

This does its job, but it's not rendering the <strong> as an actual HTML element.

So it looks (rendered) something like:

This is my string body with <strong>test</strong>,<strong>word1</strong>....

My return is:

return (
    <React.Fragment>
        {formatted}
    </React.Fragment>
}

Where I actually want the words to be bolded. How do I get react to actually render as html here? Or am I going about this wrong?

Upvotes: 0

Views: 81

Answers (3)

Rocker Feller Jr
Rocker Feller Jr

Reputation: 1

Remove the string literal so it is <span>{word} </span>

Upvotes: 0

Jumshud
Jumshud

Reputation: 1425

Try this one:

<div dangerouslySetInnerHTML={{ __html: htmlText }}>

Upvotes: 1

andsilver
andsilver

Reputation: 5972

dangerouslySetInnerHTML - pass the string into this prop.

<div dangerouslySetInnerHTML={formatted} ... />

Upvotes: 0

Related Questions