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

12277 views

AuthorΒ΄s Dominik Sumer image

Dominik Sumer

πŸ‘€
1
Last edited on

3 Answers

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

We need _document.js file in our pages folder with this structure ->

import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head />
        <body>
          <Main />
          <NextScript />
          <div id="notifications"></div>
        </body>
      </Html>
    );
  }
}

export default MyDocument;

and with that file we have place where to inject portal(in my case div with id="notifications".

πŸ‘
1
πŸ‘€
1
AuthorΒ΄s Yevgen Gorbunkov image
This video does not address SSR problem, whatsoever. As a result of demonstrated implementation no portal contents will be rendered server-side, then once JavaScript is loaded, DOM is modified accordingly.
Β (edited)