Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append React with Redux component into iframe

I have React component what use Redux Store. In componentDidMount this component should also add other component into iframe. This iframe is independent not created in component code.

<iframe src="empty.html"></iframe>

componentDidMount(){
    let iframe = document.querySelector('iframe');
    let iframeBody = iframe.contentWindow.document.body;
    let el = iframe.contentWindow.document.createElement('div');
    iframeBody.appendChild(el);
    ReactDOM.render(<ReactRedux.Provider store={store}><SkCanvas /></ReactRedux.Provider>,iframeBody.querySelector('div'));
  }

This code don't throw any errors. In new component SkCanvas is console.log with props and this log is display in my console. Just html code it's visible inside iframe. Of course if I try add this component to any element outside iframe it works.

Any hint how can I add it there?

It also possible to set this component manually into ifrmae (on init) but I need to share store between this components.

Thanks in advance for any hints.

like image 711
jaroApp Avatar asked Sep 18 '25 18:09

jaroApp


1 Answers

React doesn't preserve context across ReactDOM.render(). So the store doesn't get shared between the components outside iframe and inside if you use 2 separate ReactDOM.render()s.
In general, if you want to render a component inside any HTML element, you can use the following pattern.

Your HTML element:

<iframe id='iframe1'></iframe>

Then js file:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';

const store = configureStore();

class SkCanvas extends Component {
  render() {
    .
    .
    .
  }
}

class FrameApp extends Component {
  render() {
    return (
      <Provider store={store}>
        <SkCanvas/>
      </Provider>
    );
  }
}

ReactDOM.render(
  <FrameApp/>,
  document.getElementById('iframe1')
);

Edit: For rendering React app into and iframe, you can use react-frame-component. This library ensures the Redux store is available inside the iframe also. See also https://github.com/ryanseddon/react-frame-component/issues/29

like image 159
Dane Avatar answered Sep 21 '25 07:09

Dane