Skip to content

Instantly share code, notes, and snippets.

@davidmroth
Last active April 30, 2022 22:53
Show Gist options
  • Save davidmroth/273e36925bb78707439bf32736f47149 to your computer and use it in GitHub Desktop.
Save davidmroth/273e36925bb78707439bf32736f47149 to your computer and use it in GitHub Desktop.
Popup Window in React
// https://medium.com/hackernoon/using-a-react-16-portal-to-do-something-cool-2a2d627b0202
imports [...]
import usePopupWindow from '<your path>/usePopupWindow'
export default function () {
const PopupWindow = usePopupWindow()
return (
<div>
<PopupWindow>
content
</PopupWindow>
</div>
)
}
import React from 'react'
import { createPortal } from 'react-dom'
export default function ({
windowName = 'DEBUG',
windowFeatures = 'width=600,height=400,resizable,scrollbars=yes,status=1',
replace = false
} = {}) {
return ({ children }) => {
const [container, setContainer] = React.useState(
document.createElement('div')
)
const newWindow = React.useRef(null)
React.useEffect(() => {
// Create container element on client-side
setContainer(document.createElement('div'))
}, [])
React.useEffect(() => {
// When container is ready
if (container) {
// Create window
newWindow.current = window.open('', windowName, windowFeatures, replace)
// Append container
newWindow.current.document.body.appendChild(container)
}
}, [container])
/*React.useEffect(() => {
// TODO: Fix!!
// Return cleanup function
//if (close) return () => newWindow.current.close()
}, [close])*/
return container && createPortal(children, container)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment