Skip to content

Instantly share code, notes, and snippets.

@cmmartin
Last active December 12, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmmartin/c970eaab5ab30786517f2e4371e2dec6 to your computer and use it in GitHub Desktop.
Save cmmartin/c970eaab5ab30786517f2e4371e2dec6 to your computer and use it in GitHub Desktop.
An example of how simple it is to create a portal in React v16+
// @flow
/* eslint-env browser */
import * as React from 'react'
import { createPortal } from 'react-dom'
type Props = {
children: React.Node,
}
export default class Portal extends React.Component<Props> {
domNode: ?HTMLDivElement = null
componentWillMount() {
this.domNode = document.createElement('div')
if (document.body) document.body.appendChild(this.domNode)
}
componentWillUnmount() {
if (this.domNode) this.domNode.remove()
}
render() {
if (this.domNode == null) return null
return createPortal(this.props.children, this.domNode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment