5
votes

I am working on a rich text editor used for converting plain html to editor content with next js for ssr. I got this error window is not defined so I search a solution to this github link

It used a dynamic import feature of next js.

Instead of importing the Editor directly import { Editor } from "react-draft-wysiwyg";

It uses this code to dynamically import the editor

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

But still I'm getting this error though I already installed this react-draft-wysiwyg module

ModuleParseError: Module parse failed: Unexpected token (19:9)
You may need an appropriate loader to handle this file type.
| import dynamic from "next/dynamic";
| var Editor = dynamic(function () {
>   return import("react-draft-wysiwyg").then(function (mod) {
|     return mod.Editor;
|   });

And this is my whole code

import React, { Component } from "react";
import { EditorState } from "draft-js";
// import { Editor } from "react-draft-wysiwyg";
import dynamic from "next/dynamic";

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

class MyEditor extends Component {
  constructor(props) {
    super(props);
    this.state = { editorState: EditorState.createEmpty() };
  }

  onEditorStateChange = editorState => {
    this.setState({ editorState });
  };

  render() {
    const { editorState } = this.state;

    return (
      <div>
        <Editor
          editorState={editorState}
          wrapperClassName="rich-editor demo-wrapper"
          editorClassName="demo-editor"
          onEditorStateChange={this.onEditorStateChange}
          placeholder="The message goes here..."
        />
      </div>
    );
  }
}

export default MyEditor;

Please help me guys. Thanks.

1
I have samo bug with log : \react-draft-wysiwyg.js:1:393) undefined window ... Is it same error point ? - Nikola Lukic
what is the error message? it think its because were rendering the component on server side where window is not defined - elpmid
actually, my code is the same as yours, and it works fine at my project - Pengin

1 Answers

-1
votes

Try to return the Editor after React updates the DOM using useEffect hook. For instance:

const [editor, setEditor] = useState<boolean>(false)
  useEffect(() => {
    setEditor(true)
  })

  return (
    <>
      {editor ? (
        <Editor
          editorState={editorState}
          wrapperClassName="rich-editor demo-wrapper"
          editorClassName="demo-editor"
          onEditorStateChange={this.onEditorStateChange}
          placeholder="The message goes here..."
        />
      ) : null}
    </>
  )