Preact: Render into iframe

Created on 24 Jan 2018  路  3Comments  路  Source: preactjs/preact

Hey,

I would like to encapsulate some of my components into an iframe. This is possible with React as they allow to render into the body of an iframe. I can't figure out if this is possible with Preact as well.

I've tried the following with Preact and React.

import { render, Component } from "preact";

export default class Iframe extends Component {
  componentDidMount() {
    render(this.props.children, this.iframe.contentDocument.body);
  }

  render() {
    return <iframe ref={node => (this.iframe = node)} />;
  }
}

React example: https://codesandbox.io/s/qzrvyn1lkq
Preact example: https://codesandbox.io/s/2xpm3z1rl0

If this is a feature or a bug which needs to be fixed/added I am more than happy to give it a go.

Most helpful comment

@k15a actually you can do something like

export default class Iframe extends Component {
  componentDidMount() {
    render(<body>{this.props.children}</body>, 
        this.iframe.contentDocument.documentElement,
        this.iframe.contentDocument.body); //Notice third parameter of render() here
  }

  render() {
    return <iframe ref={node => (this.iframe = node)} />;
  }
}

It will render children into body without wrapping them

All 3 comments

hi @k15a!
this.props.children is an array and preact (currently) doesn't supprt rendering arrays of vnodes.
As a workaround you can wrap it within a new "parent" vnode for example a <div></div> .
I updated your example to show it working: https://codesandbox.io/s/50v8yqpnvl

@Kanaye Ohh yeah I forgot. Thank you very much.

@k15a actually you can do something like

export default class Iframe extends Component {
  componentDidMount() {
    render(<body>{this.props.children}</body>, 
        this.iframe.contentDocument.documentElement,
        this.iframe.contentDocument.body); //Notice third parameter of render() here
  }

  render() {
    return <iframe ref={node => (this.iframe = node)} />;
  }
}

It will render children into body without wrapping them

Was this page helpful?
0 / 5 - 0 ratings

Related issues

skaraman picture skaraman  路  3Comments

simonjoom picture simonjoom  路  3Comments

noise-machines picture noise-machines  路  3Comments

marcosguti picture marcosguti  路  3Comments

adriaanwm picture adriaanwm  路  3Comments