1

I'm building with react and I want to display JSON data returned from a get request to the user. The JSON data contains string values which are made up of sentences with html appearing within the sentences. For example:

[{ "sentence" : "Don't look at the <span> sun </span> directly with your <span>eye</span>s, it's <span>risk</span>y!"}]

My goal is for the text to render normally, but the html within the string to be rendered as html alongside the text, thus allowing me to manipulate the html so I can do things like highlight particular words within the sentence with CSS. Currently I just get the data from a get request, save it to state and display it through props like normal.

return (
    <div>{props.data.sentence}</div>
);

However if I take this value from my props and just try to include it directly in the view, it will just display the whole thing as a string thus showing the user the actual HTML code.

Can someone tell me how to display this kind of string + html combo in React?

DC1477
  • 311
  • 6
  • 13
  • Please read about XSS and DOM-based XSS before you do this. And you might want to also have a look at [DOMPurify](https://github.com/cure53/DOMPurify) – Andreas Nov 14 '20 at 10:13

1 Answers1

1

Use dangerouslySetInnerHTML

<div dangerouslySetInnerHTML={{ __html: props.data.sentence}}></div>
wangdev87
  • 8,611
  • 3
  • 8
  • 31