Skip to content

Instantly share code, notes, and snippets.

@miresk

miresk/portal.js Secret

Last active September 9, 2021 04:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miresk/abe67ef6ab1f8e76675d0a1fe44170ce to your computer and use it in GitHub Desktop.
Save miresk/abe67ef6ab1f8e76675d0a1fe44170ce to your computer and use it in GitHub Desktop.
gatsby-portal
// Example from gatsby-plugin-portal
// https://www.gatsbyjs.com/plugins/gatsby-plugin-portal/?=gatsby-plugin-portal#gatsby-gotcha---document-is-undefined
import { Component } from 'react'
import ReactDOM from 'react-dom'
// Use a ternary operator to make sure that the document object is defined
const portalRoot = typeof document !== `undefined` ? document.getElementById('portal') : null
export default class Portal extends Component {
constructor() {
super()
// Use a ternary operator to make sure that the document object is defined
this.el = typeof document !== `undefined` ? document.createElement('div') : null
}
componentDidMount = () => {
portalRoot.appendChild(this.el)
}
componentWillUnmount = () => {
portalRoot.removeChild(this.el)
}
render() {
const { children } = this.props
// Check that this.el is not null before using ReactDOM.createPortal
if (this.el) {
return ReactDOM.createPortal(children, this.el)
} else {
return null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment