I have this specific need to listen to a custom event in the browser and from there, I have a button that will open a popup window. I\'m currently using React Portal to open
const [containerEl] = useState(document.createElement('div'));
EDIT
Button onClick event, invoke first call of functional component PopupWindowWithHooks and it works as expected (create new <div>
, in useEffect append <div>
to popup window).
The event refresh, invoke second call of functional component PopupWindowWithHooks and line const containerEl = document.createElement('div')
create new <div>
again. But that (second) new <div>
will never be appended to popup window, because line externalWindow.document.body.appendChild(containerEl)
is in useEffect hook that would run only on mount and clean up on unmount (the second argument is an empty array []).
Finally return ReactDOM.createPortal(props.children, containerEl)
create portal with second argument containerEl - new unappended <div>
With containerEl as a stateful value (useState hook), problem is solved:
const [containerEl] = useState(document.createElement('div'));
EDIT2
Code Sandbox: https://codesandbox.io/s/l5j2zp89k9