Saem
Saem

Reputation: 197

React not turning HTML string from JSON into text

I am having a problem with React.js and the way it deals with text stored in variable.

Here is how it would look like using DOM:

let text = "Must credit to &quot;https://indepthguide.com/&quot; not Flickr.\nCopy Link Address: <a href=\"https://indepthguide.com/\" rel=\"nofollow\">indepthguide.com/</a>"

document.getElementById("root").innerHTML = text;
<p id="root"></p>

This is how it looks like in React.js.

var text = "Must credit to &quot;https://indepthguide.com/&quot; not Flickr.\nCopy Link Address: <a href=\"https://indepthguide.com/\" rel=\"nofollow\">indepthguide.com/</a>";

class Text extends React.Component {
  render() {
    return <h3 >{
      text
    } < /h3>;
  }
}


ReactDOM.render( <
  Text / > ,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

I have tried new DOMParser(); but with no success as it started throwing errors and i am unsure how to deal with it. I really don't know how to do it, tried doing it for very long now :D.

Upvotes: 3

Views: 2955

Answers (4)

Anand Deep Singh
Anand Deep Singh

Reputation: 2620

There is another plugin which helps HTML tags to render on the page.

https://www.npmjs.com/package/react-html-parser

In my opinion, it is a much easier way as compare to dangerouslySet InnerHTML.

Upvotes: 0

Mike Kor
Mike Kor

Reputation: 876

To all other answers it's good to add that you should protect such parts from script injection attacks. The library like DomPurify should help you with that.

Upvotes: 0

connexo
connexo

Reputation: 56753

As a last resort, you always have the ability to insert raw HTML.

<div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

https://shripadk.github.io/react/docs/jsx-gotchas.html

var text = "Must credit to &quot;https://indepthguide.com/&quot; not Flickr.\nCopy Link Address: <a href=\"https://indepthguide.com/\" rel=\"nofollow\">indepthguide.com/</a>";

class Text extends React.Component {
  render() {
    return <h3 dangerouslySetInnerHTML={{__html:text}} />
  }
}

ReactDOM.render( <
  Text / > ,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 6

Yozi
Yozi

Reputation: 12727

By default, React does not allow create tags from string variables because this is too dangerous. You could use dangerouslysetinnerhtml if it is rly necessary. Please read documentation by this link https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Upvotes: 7

Related Questions