Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 276
Saem Avatar asked Jun 12 '26 19:06

Saem


2 Answers

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

like image 115
Yozi Avatar answered Jun 14 '26 09:06

Yozi


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>
like image 23
connexo Avatar answered Jun 14 '26 09:06

connexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!