Ask Question

How can I use React Portals with NextJS SSR?

I am struggling getting portals to run in my server side code, as a portal needs to be rendered on a DOM Node and this is not available on the server side. Are there any solutions for this?

ReactNextJSserver-side-rendering

157 views

AuthorΒ΄s Dominik Sumer image

Dominik Sumer

πŸ‘€
1
Last edited on

1 Answer available

Best answer

As fetching DOM Nodes is not working on the server side obviously, my current solution is to run it on the client side only.

Here you can see a snippet of my code:

const Banner = () => {
  return ReactDOM.createPortal(
    <div>I am an awesome banner</div>,
    document.getElementById('banner-container'),
  );
};

export const PageContent = () => {
  const [showBanner, setShowBanner] = useState(false);

  useEffect(() => {
    if (!isServerSide()) {
      setShowBanner(true);
    }
  }, []);

  return (
    <>
      {showBanner && <Banner />}
    </>
  );
};

Would be nice if someone can provide an example if he managed to get Portals running with Server Side Rendering too. 😊

πŸ‘
1
πŸŽ‰
1
Last edited on