As I can see, you have 2 problems to solve here. First, how to set the innerHTML element in React. Another way is to get specific HTML for rendering depending on the given variable (for example, the current route, entering a text field, etc.).
1. Setting innerHTML element
You can do this with dangerouslySetInnerHTML prop. As the name suggests, it sets the innerHTML specified element according to what you specify ... and yes, the "dangerous" is accurate, as it is intended to make you think twice before using this function.
The official documentation reads as follows:
Misuse of innerHTML may open you up to cross-site scripting (XSS) attacks. Sanitizing user input for display is generally error prone, and failure to properly disinfect is one of the leading causes of Internet vulnerabilities on the Internet.
Check out the demo or snapshot below.
var Demo = React.createClass({ getInitialState: function() { return {showExternalHTML: false}; }, render: function() { return ( <div> <button onClick={this.toggleExternalHTML}>Toggle Html</button> {this.state.showExternalHTML ? <div> <div dangerouslySetInnerHTML={this.createMarkup()} ></div> </div> : null} </div> ); }, toggleExternalHTML: function() { this.setState({showExternalHTML: !this.state.showExternalHTML}); }, createMarkup: function() { return {__html: '<div class="ext">Hello!</div>'}; } }); ReactDOM.render( <Demo />, document.getElementById('container') );
.ext { margin-top: 20px; width: 100%; height: 100px; background: green; color: white; font-size: 40px; text-align: center; line-height: 100px; }
<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="container"></div>
2. Getting HTML from an external source
Please note that the above example does not actually output HTML from an external file, but is entered directly as a string.
One easy way to dynamically select a specific file is to allow your server (e.g. php) to read the file from the local folder, parse the text and send it back through an AJAX request.
Example
//Your React component fetchExternalHTML: function(fileName) { Ajax.getJSON('/myAPI/getExternalHTML/' + fileName).then( response => { this.setState({ extHTML: response }); }, err => { //handle your error here } ); }
Chris source share