Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,80 @@ class Form extends Component {
}
```

### iframes & document context
In cases were you need to render the portal inside of an `iframe`, you need to provide
the prop `getDocument` which is a method that return the `document` as the context of the portal.

Here is an example:

```js

const INITIAL_CONTENT = '<!DOCTYPE html><html><head></head><body><div id="frame-root"></div></body></html>';

class Iframe extends React.Component {
node = null;
initialContentRendered = false;

getDocument = () => this.node.contentDocument;

componentDidMount() {
const doc = this.getDocument();
if (doc && doc.readyState === 'complete') {
this.forceUpdate();
} else {
this.node.addEventListener('load', this.handleLoad);
}
}

componentWillUnmount() {
this.node.removeEventListener('load', this.handleLoad);
}

handleLoad = () => {
this.forceUpdate();
};


renderContent() {
if (!this.isMounted()) {
return null;
}

const doc = this.getDocument();

if (!this.initialContentRendered) {
doc.open('text/html', 'replace');
doc.write(INITIAL_CONTENT);
doc.close();
this.initialContentRendered = true;
}

return (
<Portal into="#frame-root" getDocument={this.getDocument}>
{this.props.children}
</Portal>
);
}

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

class App extends React.Component {
render() {
return (
<Iframe>
<h1>I am inside a friendly iframe</h1>
</Iframe>
);
}
}
```

[preact]: https://github.com/developit/preact
[Demo #1]: http://jsfiddle.net/developit/bsr7gmdd/
Expand Down
9 changes: 8 additions & 1 deletion src/preact-portal.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,14 @@ export default class Portal extends Component {
}

findNode(node) {
return typeof node==='string' ? document.querySelector(node) : node;
return typeof node==='string' ? this.getDocument().querySelector(node) : node;
}

getDocument() {
if (this.props.getDocument) {
return this.props.getDocument();
}
return document;
}

renderLayer(show=true) {
Expand Down