0

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?

5
  • 3
    Well how is it being rendered? You are missing the important step. Commented Jul 17, 2020 at 18:55
  • Try this const formatted = string.replace("[WORDS]", words.join(',')); Commented Jul 17, 2020 at 18:56
  • @epascarello its rendered as <strong>test</strong>.... not actually bolded Commented Jul 17, 2020 at 18:57
  • How is it being rendered? What code is displaying it? You show you building the string which clearly is not the issue. The issue is the rendering of that string. Commented Jul 17, 2020 at 18:58
  • reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml Commented Jul 17, 2020 at 19:00

3 Answers 3

1

Try this one:

<div dangerouslySetInnerHTML={{ __html: htmlText }}>
Sign up to request clarification or add additional context in comments.

Comments

0

dangerouslySetInnerHTML - pass the string into this prop.

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.