React: How to Load and Render External HTML File

How to load an HTML document in React

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.

Rendering external HTML/React components dynamically in React

Interesting problem!

You should try react-jsx-parser. I think it solves your problems. Not sure how it works with Next JS - I have no experience with Next JS.

Check out this sandbox: Edit 24r1ypp00p


You are right about all the components getting bundled. There is a workaround for that. :)

Check out this sandbox: Edit 24r1ypp00p

I've created a dynamicComponent that expects an import promise and returns a component.

I changed the way A, B and C components are imported in index.js. This way each dynamically imported component gets a separate bundle and is only requested when needed.

This should solve your second problem.

how to import HTML file into React component and use it as a component?

You can import or require the html file and use it in the src attribute,

var perf =require('./template.html');

class Index extends React.Component {
render(){
return (
<iframe src={perf }></iframe> /* like this */
);
}
}
export default Index;


Related Topics



Leave a reply



Submit