The way I see it is that you have 2 problems to solve here. The first is how to set the innerHTML of an element in React. The other is how to get a specific HTML to render depending on a given variable (e.g the current route, the input of a textfield, etc).

1. Setting the innerHTML of an element

You can do this with the dangerouslySetInnerHTML prop. As the name suggests it sets the innerHTML of the said element to whatever you specify... and yes, the "dangerously" is accurate as it's intended to make you think twice before using this feature.

The Official Documentation reads as follows:

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

Check out this Demo or the snippet 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. Fetching the HTML from an external source

Note that the above example does not actually get the HTML from an external file, but is entered directly as a string.

One simple way to do dynamically fetch a choose a specific file would be to let your backend (e.g php) read the file from a 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
    }
  );
}
Answer from Chris on Stack Overflow
Top answer
1 of 5
30

The way I see it is that you have 2 problems to solve here. The first is how to set the innerHTML of an element in React. The other is how to get a specific HTML to render depending on a given variable (e.g the current route, the input of a textfield, etc).

1. Setting the innerHTML of an element

You can do this with the dangerouslySetInnerHTML prop. As the name suggests it sets the innerHTML of the said element to whatever you specify... and yes, the "dangerously" is accurate as it's intended to make you think twice before using this feature.

The Official Documentation reads as follows:

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

Check out this Demo or the snippet 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. Fetching the HTML from an external source

Note that the above example does not actually get the HTML from an external file, but is entered directly as a string.

One simple way to do dynamically fetch a choose a specific file would be to let your backend (e.g php) read the file from a 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
    }
  );
}
2 of 5
21

While Chris's answer was good, some more digging was required to make it work. Here are the steps that you need to take:

Add html loader to your project:

npm i -D html-loader

Add the following rule to your webpack.config file:

{
  test: /\.(html)$/,
  use: {
    loader: 'html-loader',
    options: {
      attrs: [':data-src']
    }
  }
}

Now you can import your html file as follow:

import React, { Component } from 'react';
import Page from './test.html';
var htmlDoc = {__html: Page};

export default class Doc extends Component {
  constructor(props){
    super(props);
  }

  render(){
     return (<div dangerouslySetInnerHTML={htmlDoc} />)
}}
🌐
GitHub
github.com › facebook › create-react-app › issues › 9046
How to load html file as string into React · Issue #9046 · facebook/create-react-app
May 21, 2020 - // pattern.jsx import React from 'react'; import html from 'statisPages/pattern.html' export default function Pattern() { return ( <div dangerouslySetInnerHtml={{ __html: html }}> </div> ); } I know I can export all HTML as string from a js file, but to do so I have to put HTML inside string literal and it's doesn't look pretty, I want to put it in a normal *.html file so others know it's a HTML. Webpack has html-loader that can do this, I tested and it worked but it required to eject.
Published   May 22, 2020
Author   ghost
Discussions

reactjs - How to load external HTML file in react components? - Stack Overflow
53 React: how to load and render external html file? More on stackoverflow.com
🌐 stackoverflow.com
How can I render HTML from another file in a React component?
https://github.com/wojtekmaj/react-pdf/issues/300#issuecomment-846226460 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 3 Rendering raw html file returns error "Module parse failed: Unexpected token (1:0) You may need an appropriate loader ... More on stackoverflow.com
🌐 stackoverflow.com
How to input external react app into main html file?
Hello, I’m new in react. So, now I know how to create react app using inline method which is using in my main html file but it won’t load in my browser (mozilla and chrome). So what did I do wrong? thanks this is my HTML file cod... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
1
July 23, 2018
reactjs - how to import HTML file into React component and use it as a component? - Stack Overflow
any ideas? How to load an HTML file inside of a React Component? How to add an appropriate loader to handle this file type? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Syncfusion
ej2.syncfusion.com › react › documentation › listview › how-to › load-html-content-via-ajax
Load html content via ajax in React ListView component | Syncfusion
ajax = new Ajax('https://helpej2.syncfusion.com/react/documentation/code-snippet/listview/ajax-cs1/template', 'GET', false); ajax.onSuccess = (e: string) => { template = e; }; ajax.send(); In the below sample, we render a smartphone settings ...
🌐
Edincitaku
edincitaku.com › 01-loading-html-file-react
Loading html files in React April 9, 2020 - edincitaku.com
The solution was quite simple, as it turns out there is a package named html-react-parser that can parse html as a string. But first I needed to get the html file as a string from my component. The backend of the webapp was written in nodejs with express, so I decided to provide an API that returns the string as a file. Here we load our file and create the function that returns the html file as a string
🌐
DEV Community
dev.to › shreyvijayvargiya › 4-steps-to-render-html-file-in-react-38h
4 steps to render HTML file in React - DEV Community
August 24, 2022 - This is a crucial step, we will ... them in the api/profile page. When the user opens the profile page, api/profileendpoint will get the request to render the profile HTML file on the website....
🌐
About React
aboutreact.com › home › load local html file or url in react native using react-native-webview
Load Local HTML File or URL in React Native using react-native-webview
December 3, 2022 - How to open any URL, Local HTML File and or any HTML in Recat native App using WebView component provided by react-native-webview.
🌐
Medium
medium.com › @muneebwaqas416 › how-to-use-reactjs-external-file-in-an-html-file-1013fd304381
How to use ReactJS External File in an HTML File | by Muneeb Waqas | Medium
January 30, 2024 - In this article, we’ve demonstrated how to integrate ReactJS into an HTML file using React CDN links and Babel for JSX transformation. This approach allows you to build React components and seamlessly incorporate them into your HTML documents without the need for a complex build setup.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 72941304 › how-to-load-external-html-file-in-react-components
reactjs - How to load external HTML file in react components? - Stack Overflow
import React from "react"; var htmlContent = require('../../assets/survey-chatbot-extension/index.html'); const Survey = () => { return ( <div dangerouslySetInnerHTML={{__html: htmlContent}}></div> ) } export default Survey; The requirement is to load the index.html file on rendering of Survey.js...
🌐
Altcademy
altcademy.com › blog › how-to-include-html-file-in-reactjs-anchor-a-tag
How to include html file in ReactJS anchor a tag
November 12, 2023 - To conclude, let's think of including an HTML file in ReactJS as packing a suitcase. You can't fit an item as it is, you need to fold it (convert HTML to string), and then you need to carefully place it inside (use dangerouslySetInnerHTML).
🌐
Gaudebert
adrian.gaudebert.fr › blog › post › 2015 › 12 › 24 › how-to-include-html-in-your-react-app-with-webpack
How to include HTML in your React app with webpack - Blog | Adrian Gaudebert
December 25, 2015 - { modules: { loaders: [ { test: /\.html$/, loader: 'html' } ] } } Then simply require your HTML file from any JS file, with var htmlContent = require('path/to/html/file.html'); or import htmlContent from 'path/to/html/file.html'); if you are using ES6. Let's say we are using babel, this is ...
🌐
DEV Community
dev.to › damcosset › rendering-html-files-in-an-express-react-react-router-application-nbk
Rendering HTML files in an Express/React/React Router application - DEV Community
March 28, 2019 - I believe, and I may be wrong, that I need to bypass the react-router directive to use response.renderFile from Express. How would I manage that? So, make a post request with the file path, open a new tab and render from express the HTML content.
🌐
GitHub
github.com › gatsbyjs › gatsby › issues › 4104
Include html file as a react component / iframe · Issue #4104 · gatsbyjs/gatsby
February 17, 2018 - I'm using Gatsbyjs (latest version) to create a demo site. On my demo site I have two solutions, one is React App and the second one is HTML app (pure html). I'd like to use gatsby as a Static Site Generator for both solutions. I'm not able to import an HTML file within react.
🌐
Pluralsight
pluralsight.com › what makes pluralsight different | pluralsight › tech guides & tutorials
How to Use Static HTML with React | Pluralsight
August 3, 2020 - If you try to render an HTML string inside a component directly, React will automatically sanitize it and render it as a plain string. const myHTML = `<h1>John Doe</h1>`; const App = () => <div>{myHTML}</div>; The above code will not render the string "John Doe" in a heading. Instead, the complete string, including the H1 tags, will be displayed to the user, thanks to React.
Top answer
1 of 6
72

If your template.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.

However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.

Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop.

var __html = require('./template.html');
var template = { __html: __html };

React.module.exports = React.createClass({
  render: function() {
    return(
      <div dangerouslySetInnerHTML={template} />
    );
  }
});

This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.

If your template.html file looked something like this

<div class='foo'>
  <h1>Hello</h1>
  <p>Some paragraph text</p>
  <button>Click</button>
</div>

Then you could convert it instead to a JSX file that looked like this.

module.exports = function(props) {
  return (
    <div className='foo'>
      <h1>Hello</h1>
      <p>Some paragraph text</p>
      <button>Click</button>
    </div>
  );
};

Then you can require and use it without needing stringify.

var Template = require('./template');

module.exports = React.createClass({
  render: function() {
    var bar = 'baz';
    return(
      <Template foo={bar}/>
    );
  }
});

It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.

2 of 6
8

You can use the dangerouslySetInnerHTML property to inject arbitrary HTML:

// Assume from another require()'ed module:
var html = '<h1>Hello, world!</h1>'

var MyComponent = React.createClass({
  render: function() {
    return React.createElement("h1", {dangerouslySetInnerHTML: {__html: html}})
  }
})

ReactDOM.render(React.createElement(MyComponent), document.getElementById('app'))
<script src="https://fb.me/react-0.14.3.min.js"></script>
<script src="https://fb.me/react-dom-0.14.3.min.js"></script>
<div id="app"></div>

You could even componentize this template behavior (untested):

class TemplateComponent extends React.Component {
  constructor(props) {
    super(props)
    this.html = require(props.template)
  }

  render() {
    return <div dangerouslySetInnerHTML={{__html: this.html}}/>
  }

}

TemplateComponent.propTypes = {
  template: React.PropTypes.string.isRequired
}

// use like
<TemplateComponent template='./template.html'/>

And with this, template.html (in the same directory) looks something like (again, untested):

// ./template.html
module.exports = '<h1>Hello, world!</h1>'
🌐
npm
npmjs.com › package › html-to-react-components
html-to-react-components - npm
January 31, 2019 - Be aware that you'll have to spend time on copying and pasting markup from DevTools into files which will be processed. extract-to-react is an extension for Chrome and Chromium browsers built on top of html-to-react-components which allows you to extract HTML and CSS into React components and load them in CodePen or JSFiddle.
      » npm install html-to-react-components
    
Published   Jan 31, 2019
Version   1.6.6
Author   Roman Liutikov
Top answer
1 of 2
1

You can use dangerouslySetInnerHTML to insert html in react component. This will render the whole html inside the div tag.

const content = `<html>
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="content-type">
    <style type="text/css">
       @import url('https://themes.googleusercontent.com/fonts/css?kit=fpjTOVmNbO4Lz34iLyptLUXza5VhXqVC6o75Eld_V98');.lst-kix_list_1-3>li:before{content:"\0025cf  "}.lst-kix_l.......
    </style>
</head>
<body class="c16">
    <div>Test</div>
</body>
</html>`


class TermsAndConditionsPage extends React.Component {
    render() {
       return <div dangerouslySetInnerHTML={{ __html: content }}/>
    }
}

From the docs:

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting > (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.

2 of 2
0

If looking for the easiest, quickest method, dangerouslySetInnerHTML will do the trick as the other answer mentions.

If you don't mind some manual work, you could use online tools like https://premailer.io/

  1. copy over all CSS declarations in the imported sheet into head area within style tag
  2. copy the entire html document into the input area at https://premailer.io/
  3. hit convert

You'll then end up with the complete html document with every CSS style inlined, which you could use as JSX.

🌐
Stack Overflow
stackoverflow.com › questions › 51240696 › is-it-possible-to-load-html-page-by-using-react-component
Is it possible to load html page by using React component?
<div className="App"> <Header/> <--React Component <LoginApp /> <--React Component <Register /> <--React Component <Footer /> <--React Component // Load other external html files here...