Opening an external html file from a react app

1.7k Views Asked by At

I have a react app, which i make thought create-react-app. I want to make here a link, that will refer to project.html file. I tried to make something like this:

const Portfolio = (props) => {
    return (
            <a href="../projects/project.html" target="_blank">
                <button>Go to this project</button>
            </a>
    )
}

But this lead me to http://localhost:3000/projects/project.html and react app. I also tried to import this path like:

import html from "../projects/project.html"

and then to do something like this:

        <a href={html} target="_blank">
            <button>Go to this project</button>
        </a>

but react say that i need some loader for this. I find that there are html-loader, i install it by npm install --save-dev html-loader and add configuration to webpack.config.js but nothing changed

2

There are 2 best solutions below

0
On

If your projects/project.html file contains only static content and does not require anything from the codebase, you could move the projects folder to the public folder, and link to that file in your React component with:

const Portfolio = (props) => {
    return (
            <a href="/projects/project.html" target="_blank">
                Go to this project
            </a>
    )
}
3
On

First install html loader using

npm install --save-dev html-loader

Add below lines to your webpack.config file

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

Now you can import like this

import Page from './project.html';
var htmlDoc = {__html: Page};

Then, in return block of react, use like this

<div dangerouslySetInnerHTML={htmlDoc} />