Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSR is not working #3

Open
damner opened this issue Oct 17, 2019 · 3 comments
Open

SSR is not working #3

damner opened this issue Oct 17, 2019 · 3 comments

Comments

@damner
Copy link

damner commented Oct 17, 2019

Error:

ReferenceError: document is not defined

@pimterry
Copy link
Member

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.

@codetheweb
Copy link

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.

@pimterry pimterry mentioned this issue Oct 7, 2021
@HynekS
Copy link

HynekS commented Jan 14, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants