Reputation: 419
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
Reputation: 1425
Try this one:
<div dangerouslySetInnerHTML={{ __html: htmlText }}>
Upvotes: 1
Reputation: 5972
dangerouslySetInnerHTML
- pass the string into this prop.
<div dangerouslySetInnerHTML={formatted} ... />
Upvotes: 0