Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window is not defined - react-draft-wysiwyg used with next js (ssr)

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.

like image 305
elpmid Avatar asked Aug 17 '20 12:08

elpmid


1 Answers

Here is a workaround

import dynamic from 'next/dynamic'
import { EditorProps } from 'react-draft-wysiwyg'

// install @types/draft-js @types/react-draft-wysiwyg and @types/draft-js @types/react-draft-wysiwyg for types

const Editor = dynamic<EditorProps>(
  () => import('react-draft-wysiwyg').then((mod) => mod.Editor),
  { ssr: false }
)
like image 187
Naimur Rahman Avatar answered Sep 20 '22 11:09

Naimur Rahman