react-reverse-portal icon indicating copy to clipboard operation
react-reverse-portal copied to clipboard

SSR is not working

Open damner opened this issue 5 years ago • 3 comments

Error:

ReferenceError: document is not defined

damner avatar Oct 17 '19 22:10 damner

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.

pimterry avatar Oct 17 '19 22:10 pimterry

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 avatar Sep 12 '21 03:09 codetheweb

@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>
  );
};

HynekS avatar Jan 14 '22 12:01 HynekS