How can I make React Portal work with React Hook?

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

    You could create a small helper hook which would create an element in the dom first:

    import { useLayoutEffect, useRef } from "react";
    import { createPortal } from "react-dom";
    
    const useCreatePortalInBody = () => {
        const wrapperRef = useRef(null);
        if (wrapperRef.current === null && typeof document !== 'undefined') {
            const div = document.createElement('div');
            div.setAttribute('data-body-portal', '');
            wrapperRef.current = div;
        }
        useLayoutEffect(() => {
            const wrapper = wrapperRef.current;
            if (!wrapper || typeof document === 'undefined') {
                return;
            }
            document.body.appendChild(wrapper);
            return () => {
                document.body.removeChild(wrapper);
            }
        }, [])
        return (children => wrapperRef.current && createPortal(children, wrapperRef.current);
    }
    

    And your component could look like this:

    const Demo = () => {
        const createBodyPortal = useCreatePortalInBody();
        return createBodyPortal(
            
    In body
    ); }

    Please note that this solution would not render anything during server side rendering.

提交回复
热议问题