Skip to content

Instantly share code, notes, and snippets.

@davidmroth
Last active Apr 30, 2022
Embed
What would you like to do?
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