3

My React application is generated by create-react-app. I am trying to display a html file content(exists under directory src/www/test.html) in react component.

Running "npm start" is throwing error:

Compiling... Failed to compile.

./src/www/test.html 1:0 Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type.

| |

React Component

import Page from '../../www/test.html';

class Example extends React.Component {

render(){
    let htmlPage = {__html : Page};
    return (<div dangerouslySetInnerHTML={htmlPage} /> );
}

}

================

test.html

<html>
<head></head>
<body>
    <h1>I'm alive!</h1>
</body>
</html>

Please note, I don't prefer to eject from create-react-app. Looking for suggestions to overcome this issue.

user3362908
  • 433
  • 5
  • 16
  • I can't be sure, but I'm pretty sure you can't import HTML files into JS. changes the HTML file to a `jsx` file with a corresponding `export` call? – Jhecht Jan 15 '19 at 01:15
  • You can when using webpack (which is used internally by `create-react-app`). I'm pretty sure that this should work since [`create-react-app` doesn't specify its own loader for `.html` files](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/config/webpack.config.js#L505) and webpack should handle `.html` files by default (returning a string of the content) – inyono Jan 15 '19 at 01:29
  • Thanks for your suggestion. Without ejecting from create-react-app how to modify the webpack config to add html loader. – user3362908 Jan 15 '19 at 01:43
  • Perhaps [This question](https://stackoverflow.com/questions/33973757/how-can-i-render-html-from-another-file-in-a-react-component) can give you some guidance. – Jhecht Jan 15 '19 at 04:06

0 Answers0