How can I make React Portal work with React Hook?

后端 未结 7 2051
感动是毒
感动是毒 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:17

    Thought id chime in with a solution that has worked very well for me which creates a portal element dynamically, with optional className and element type via props and removes said element when the component unmounts:

    export const Portal = ({
      children,
      className = 'root-portal',
      element = 'div',
    }) => {
      const [container] = React.useState(() => {
        const el = document.createElement(element)
        el.classList.add(className)
        return el
      })
    
      React.useEffect(() => {
        document.body.appendChild(container)
        return () => {
          document.body.removeChild(container)
        }
      }, [])
    
      return ReactDOM.createPortal(children, container)
    }
    
    

提交回复
热议问题