17

I'm using Next.js with my React app, and I'm having a trouble with creating modal in portal, it throws an error 'Target container is not a DOM element.', here is my code.

import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import classes from './listModal.scss';

const EditorListModal = (props) => {
  let container;
  if (typeof window !== 'undefined') {
    const rootContainer = document.createElement('div');
    const parentElem = document.querySelector('#__next');
    parentElem.appendChild(rootContainer);
    container = rootContainer;
  }
  const isShown = props.show ? classes['editor-listModal--open'] : '';
  const element = (
    <div className={`${classes['editor-listModal']} ${isShown}`}>
      // Modal Content
    </div>
  );

  return ReactDOM.createPortal(element, container);
};

EditorListModal.propTypes = {
  show: PropTypes.bool
};

export default React.memo(EditorListModal);
tanguy_k
  • 11,307
  • 6
  • 54
  • 58
Armen Nersisyan
  • 313
  • 2
  • 3
  • 11

2 Answers2

26

Accepted answer is not the best option. You may have lots of render issues when server rendered content differs from the client's. The main idea is to have the same content during SSR and hydration. In your case it would be more accurate to load modal dynamically with { ssr: false } option.

As the second option take a note at next's example. There they always return null during initial render both on server and client and that's a correct approach.

likerRr
  • 1,248
  • 1
  • 13
  • 19
  • I upvote. If you expand on the render issues caused by different content during different renders, I guess it would be very helpful for those who come across this question. – Evgeny Timoshenko May 03 '21 at 17:26
  • 1
    @EvgenyTimoshenko I think it would be enough to put this [link](https://reactjs.org/docs/react-dom.html#hydrate) here with a single quote: "you should treat mismatches as bugs and fix them" – likerRr Jun 01 '21 at 21:38
  • Thanks for that link to the NextJs official modal implementation – sayandcode Nov 22 '22 at 09:16
12

It's going to break during the ssr because the container is not initialized. You could try to skip rendering when there is no portal:

return container ? ReactDOM.createPortal(element, container) : null;
tanguy_k
  • 11,307
  • 6
  • 54
  • 58
Evgeny Timoshenko
  • 3,119
  • 5
  • 33
  • 53