Maksym Popov
Maksym Popov

Reputation: 452

How to import external html file to React app?

I have a project in a middle of development. And I need to use external landing page as a home page. Therefore, I need to import landings index.html, but it has its own folders with css and js(mainly Jquery code).

I wanted to import it as <iframe src={html}></iframe> into my project but my app doesn't seem to load htmls.

What are best ways to import html files that use own jquery code to react?

Upvotes: 1

Views: 9443

Answers (3)

Arnab_Ghosh
Arnab_Ghosh

Reputation: 319

I was also trying to find out a solution and figured out two ways for different use cases:

  1. If your HTML file contains <div> and other child tags (that can be nested under other <div> or <body> tags) then this approach will work for you:
  • First you need to configure webpack to be able to parse HTML files. You can either do that with npm eject or use another module react-app-rewired - and then add a HTML loader in overrides.

  • Then import the HTML file and use a parser. I believe it's better than using dangerouslySetInnerHTML.

Example with Method 1:

    const parse = require("html-react-parser");
    const docs = require("../../public/redoc-static.html").default;
    
    const ApiDocs = (props: any) => {    
      return (
        <Box sx={{ display: "flex", height: "100vh" }}>
            <Box>{parse(docs)}</Box>
          </Box>
      );
    };

  1. If your HTML file contains a <html> tag (is a complete file) following the above approach would give the very obvious error <html> cannot appear as a child of <div>. In that case, the workaround I found is to open the whole HTML file in a different tab of the browser with _blank:

Example with Method 2:

window.open(filename, "_blank")

Note: The HTML file has to reside in the public folder of your project.

Upvotes: 0

user15919322
user15919322

Reputation:

I'm just going to through this out there as a spitball... I've never tried it, but why not directly replace index.html and not render anything on that page? You would have to either adjust the build somehow... I have no idea how to, or manually put it after the react app finishes building. I'm sure it would be a bug nightmare, but it honestly sounds a little less of a hastle than an iframe which might give you some weird UI behavior. React-Server, even though it says server, really just takes stringified JSX and I think html translates it back to workable code. You could also try that approach, but this does sound like a nightmare project.

Upvotes: 0

Juan Marco
Juan Marco

Reputation: 3241

This is a bit tricky, and there might be other ways (perhaps better) to achieve the same result. Also, I would consider the performance impact of loading multiple libraries into an existing React app.

With that humble disclaimer out of the way, one way to do this would be to include jQuery directly into React's main index.html page using <script> tags, this will make $ globally available across the app:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>

  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  </body>
</html>

Once this is done, place the landing page project folder (along with its dependencies) inside the public directory:

project folder layout

Then, from the main app component load the desired landing page using fetch, then use .text() to transform the retrieved page into regular text.

Use setState to set the retrieved HTML into the app state, then inside render() use a regular <div> container to store the landing page and use the React attribute dangerouslySetInnerHTML to set HTML inside that target container.

Finally, I pass an anonymous function (as a second parameter to setState) and use jQuery's getScript() to load and execute the required JS libraries that the landing page depends on.

In the example, I loaded Bootstrap's JS, which is needed to power the Carousel.

Bootstrap's CSS is loaded directly from the landing page's HTML file using a standard <link> tag.

import React from "react";

class App extends React.Component {
  state = {
    page: null
  };

  componentDidMount() {
    fetch("landing-page-one/index.html")
      .then(result => {
        return result.text();
      })
      .then(page => {
        this.setState(
          {
            page: { __html: page }
          },
          () => {
            window.$.getScript("landing-page-one/js/index.js");
          }
        );
      });
  }

  render() {
    const { page } = this.state;
    return (
      <>
        <h2>
          <span>Inserting project using React's </span>
          <code>dangerouslySetInnerHTML</code>:
        </h2>
        <div
          dangerouslySetInnerHTML={page && page}
        />
      </>
    );
  }
}

export default App;

Working example here.

Upvotes: 3

Related Questions