Ruslan
Ruslan

Reputation: 41

NextJS - ReferenceError: window is not defined

import dynamic from 'next/dynamic'
import { convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToMarkdown from 'draftjs-to-markdown';
import ReactMarkdown from 'react-markdown'

When I refresh page, it happens error: ReferenceError: window is not defined

I follow the solution and changed code as follow:

const { convertToRaw } = dynamic(import('draft-js'),{ssr:false})
const { Editor } = dynamic(import('react-draft-wysiwyg'),{ssr:false})

const draftToMarkdown = dynamic(() => import("draftjs-to-markdown"), {
  ssr: false
});
const ReactMarkdown = dynamic(() => import("react-markdown"), {ssr:false})

But this time, it doesn't display, nothing, it is blank page Please find the solution

Upvotes: 4

Views: 7885

Answers (2)

serenomateus
serenomateus

Reputation: 26

I'm a little late to the party but I recently fixed this issue with the following code:

WysiwygEditor.tsx

import dynamic from 'next/dynamic'
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const Editor = dynamic(
  async () => {
    const mod = await import("react-draft-wysiwyg");
    return mod.Editor;
  },
  { ssr: false }
);


export default function WysiwygEditor() {
  return (
    <Editor />
  );
}

If you want a detailed explanation as to WHY the "window is not defined" error occurs, refer to this blog page. It talks about the basic case when Next.js trying to pre-render (server side) a piece of code that needs to access "window".

Our case is a little bit more specific, since the reference to the "window" is done in an imported module. This means we have no control over "the piece of code that uses 'window'". Therefore we must use Next's dynamic import

Upvotes: -1

felixmosh
felixmosh

Reputation: 35573

Since Next.js runs on the server & client, you need to make sure that your code access window object only when it runs in the client.

There are 2 things that runs on the client for sure, event handles & useEffect hook / componentDidMount.

Put your window related code there.

Upvotes: 1

Related Questions