how to use iframe in react.js

Viewed 27215

how can i require html from public/ with iframe?

my code like this:

 App.js

import React, {Component} from 'react';
import Iframe from './IframeComm';

class App extends Component {
    render() {
        return (
            <div className="App">
                <h1>react</h1>
                <Iframe
                    attributes={
                        {
                            src: '/test/test.html',
                            style: {
                                border: '10px solid red'
                            },
                        }
                    }
                />
            </div>
        );
    }
}

export default App;

test.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    iframe
</body>
</html>

when i usenpm start,everything allright

enter image description here

but when i use npm run build

enter image description here

toc:

enter image description here

how can i fixed this?thanks.

2 Answers

You can simply create a new component that take source and return with Iframe;

iframe.js

import React from 'react';

const Iframe = ({ source }) => {

    if (!source) {
        return <div>Loading...</div>;
    }

    const src = source;     
    return (
        // basic bootstrap classes. you can change with yours.
        <div className="col-md-12">
            <div className="emdeb-responsive">
                <iframe src={src}></iframe>
            </div>
        </div>
    );
};

export default Iframe;

Then you can simply call that component like;

import React, {Component} from 'react';
import Iframe from './components/iframe.js';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            src: '/test/test.html'
        };
    }

    render() {
        return (
            <div className="App">
                <h1>react</h1>
                <Iframe source={this.state.src} />
            </div>
        );
    }
}

export default App;

If you want to keep the html in public folder, do an axios call, load the html into a variable and give it in the src,

var myhtml;
axios.get('/test/test.html').then((resp)=>{
  myhtml = resp.data;
})
...
<Iframe
attributes={
              {
                 src: {myhtml},
                 style: {
                          border: '10px solid red'
                        },
               }
            }
 />

Or, you can add the htmlfile to the src folder instead of public and use it like you have done.

Related