Created
May 19, 2020 20:03
-
-
Save josephdburdick/e00881678d9af706fc93768a53eb2e10 to your computer and use it in GitHub Desktop.
Nested Portals + SSR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
const PortalContext = React.createContext( | |
typeof document !== "undefined" ? document.body : null | |
); | |
export function Portal({ children }) { | |
// if it's a nested portal, context is the parent portal | |
// otherwise it's document.body | |
const context = React.useContext(PortalContext); | |
const [container] = React.useState(() => { | |
if (typeof document !== "undefined") { | |
const portal = document.createElement("div"); | |
portal.className = "portal"; | |
return portal; | |
} | |
// ssr | |
return null; | |
}); | |
React.useLayoutEffect(() => { | |
if (container && context) { | |
context.appendChild(container); | |
return () => { | |
context.removeChild(container); | |
}; | |
} | |
return undefined; | |
}, [container, context]); | |
if (container) { | |
const portal = ReactDOM.createPortal(children, container); | |
return ( | |
<PortalContext.Provider value={container}> | |
{portal} | |
</PortalContext.Provider> | |
); | |
} | |
// ssr | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment