1

I have created a context component in React to return a message across all my React pages.

I am getting the error in the subject. Looked at other questions in stackoverflow but none could help me.

Here is the code:

message.js

function Message(props) {
const messageCtx = useContext(MessageBannerContext);

    return ReactDOM.createPortal(
        <div>
            <p>Message</p>
            <button>More info</button>
            <button onClick={messageCtx.hideMessage}>Ok</button>
        </div>,
        useEffect(() => {
            document.getElementById('message');
        }, [])
    );
}

export default Message;

_document.js

class MyDocument extends Document {

    render() {
        return (
            <Html>
                <Head />
                <body>
                    <Main />
                    <DeferNextScript />
                </body>
                <div id="message"></div>
            </Html>
        );
    }
}

export default MyDocument;

Any ideas why I am getting the error in the subject?

RandomDeveloper
  • 833
  • 2
  • 9
  • 31
  • You're passing a `useEffect` call as second argument to `ReactDOM.createPortal` but it expects a DOM node instead. – juliomalves Aug 24 '21 at 14:42
  • Does this answer your question: [Getting "Target container is not a DOM element" error when using createPortal in Next.js](https://stackoverflow.com/a/69361050/1870780)? – juliomalves Oct 30 '21 at 11:53

2 Answers2

1

I had this same issue. You have to import createPortal from 'react-dom' and drop ReactDom. from the return statement like so:

import { createPortal } from 'react-dom';
function Message(props) {
const messageCtx = useContext(MessageBannerContext);

    return createPortal(
        <div>
            <p>Message</p>
            <button>More info</button>
            <button onClick={messageCtx.hideMessage}>Ok</button>
        </div>,
        useEffect(() => {
            document.getElementById('message');
        }, [])
    );
}

export default Message;
tdy
  • 36,675
  • 19
  • 86
  • 83
0

Nextjs is run in the server, so the Document Object isn't defined. I've always struggled with that, however you can try a package named jsdom.