0

I'm new to React js and I'm getting data from an API that I want to display on the page. However the string I would like to display has HTML tags inside the string. example:

"<p>Portal 2 is a first-person puzzle game.</p> <p>Its plot directly follows the first game&#39;s, taking place in the Half-Life universe.</p> <br />"

How would I go about displaying this on the page, so that it automatically turns the HTML tags into the formatting it's supposed to be, like this:

"

Portal 2 is a first-person puzzle game.

Its plot directly follows the first game's, taking place in the Half-Life universe.


"

Note: I prefer to stay away from Jquery. I'd like the code to be written in an easy to understand way, as I'm still learning.

1 Answers1

0

You'll want to use dangerouslySetInnerHTML in order to display it as plain HTML.

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Of course, make sure to be careful of exposing yourself to XSS attacks if you're using this for something more than a side project.

  • Thanks so much! Yes, this worked! However, out of curiosity, if this was used for a job, how would you do this withought exposing yourself to attacks? – Paige Andrews Apr 06 '20 at 18:23
  • Ideally, you'd set up the api so it just sends data instead of fully formatted HTML. If you can't get around that though, you could use a library to sanitize the HTML to keep it safe. This post is a good place to learn more about that: https://dev.to/jam3/how-to-prevent-xss-attacks-when-using-dangerouslysetinnerhtml-in-react-1464 If this worked for you, I'd really appreciate it if you could select it as the answer :D – Bastion the Dev Apr 06 '20 at 19:07