Skip to content

Instantly share code, notes, and snippets.

@josephdburdick
Created May 19, 2020 20:03
Show Gist options
  • Save josephdburdick/e00881678d9af706fc93768a53eb2e10 to your computer and use it in GitHub Desktop.
Save josephdburdick/e00881678d9af706fc93768a53eb2e10 to your computer and use it in GitHub Desktop.
Nested Portals + SSR
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