react-reverse-portal
react-reverse-portal copied to clipboard
SSR is not working
Error:
ReferenceError: document is not defined
Yes, that makes sense. I'm not doing SSR myself at all, so I'm unlikely to look at this any time soon, but I'd happily accept PRs.
Although it should be doable I suspect it's complicated to make everything work nicely server side, so as a very first step I'd suggest we simply avoid crashing but render nothing at all, and leave it all to be rendered on the client.
Note for anyone else who runs into this:
I took a similar approach as @pimterry suggests and did something like this:
const [shouldRenderTable, setShouldRenderTable] = useState(false);
useEffect(() => {
setShouldRenderTable(true);
}, []);
const portalNode = useMemo(() => {
if (!shouldRenderTable) {
return null;
}
return portals.createHtmlPortalNode();
}, [shouldRenderTable]);
...
return (
<div>
{
portalNode && (
<portals.InPortal node={portalNode}>
<ChildToRender/>
</portals.InPortal>
)
}
...
{
portalNode && (
<portals.OutPortal node={portalNode}/>
)
}
</div>
)
Seems to work fine.
@codetheweb Nice solution, thank you. For me, even slightly simpler version works (Gatsby site):
const MyComponent = () => {
const isSSR = typeof window === "undefined";
const portalNode = useMemo(() => {
if (isSSR) {
return null;
}
return portals.createHtmlPortalNode();
}, []);
return (
<div>
{portalNode && (
<portals.InPortal node={portalNode}>
<ChildToRender />
</portals.InPortal>
)}
...
{portalNode && <portals.OutPortal node={portalNode} />}
</div>
);
};