4
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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply, It runs window.alert() Can you explain me in detail?
Ok, as I've explained, window object exists only in the browser, therefore, you need ensure that this code runs either in useEffect of componentDidMount
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.