Sunny
Sunny

Reputation: 478

How to render the HTML into react component

I want to render the pure HTML coming from some external source into react component. I saw few solutions where people are talking about some conversion tools (HTML to JSX) but I want to handle everything in my component so while mounting it will get the HTML response and that needs to render.

Upvotes: 0

Views: 952

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282130

This shouldn't be difficult to do . Assign your HTML to a div and then render it using {variable name} JSX allows you to do this and with ES6 integration you can also use class instead of className.

var Hello = React.createClass({
  
  render: function() {
  var htmlDiv = <div>How are you</div>
    return <div>Hello {this.props.name}
    		{htmlDiv}
    </div>;
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>


<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Upvotes: 0

Christoph
Christoph

Reputation: 1630

You can use dangerouslySetInnerHTML for this:

function createMarkup() { return {__html: 'First &middot; Second'}; };
<div dangerouslySetInnerHTML={createMarkup()} />

But as the method name suggests: you should be very sure of what you are doing there and the security implications it has.

Upvotes: 1

Related Questions