How can I make React Portal work with React Hook?

后端 未结 7 2014
感动是毒
感动是毒 2021-01-01 22:05

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

相关标签:
7条回答
  • 2021-01-01 22:33

    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

    0 讨论(0)
提交回复
热议问题