0

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.

2 Answers 2

1

You can use dangerouslySetInnerHTML for this:

function createMarkup() { return {__html: 'First · 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yup.. if you dont know the source never use. If someone embeds a malicious Javacript inside html and you call that API, there can be consequences
I am using 'react-HTML-parser' which rendering HTML into reactJS component properly but now I am facing another issue. It requires HTML as a string and I am not sure how to stringify HTML? Example: I want '<div>Hello</div> instead of <div>Hello</div>
0

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>

1 Comment

This only works with predefined elements, not with a HTML string coming from an external source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.