17

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.

3
  • I have samo bug with log : \react-draft-wysiwyg.js:1:393) undefined window ... Is it same error point ? Commented Apr 1, 2021 at 10:06
  • what is the error message? it think its because were rendering the component on server side where window is not defined Commented Apr 2, 2021 at 13:27
  • 1
    actually, my code is the same as yours, and it works fine at my project Commented Jul 16, 2021 at 1:15

5 Answers 5

18

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 }
)
Sign up to request clarification or add additional context in comments.

2 Comments

The dynamic import fixes the window not being defined error while installing types and using EditorProps fixed the type error in Typescript
With this solution I have a type error: Argument of type '() => Promise<ComponentClass<EditorProps, any> | FunctionComponent<EditorProps> | ComponentModule<EditorProps> | typeof Editor>' is not assignable to parameter of type 'DynamicOptions<EditorProps> | Loader<EditorProps>'.
9

The dynamic one worked for me

import dynamic from 'next/dynamic';
const Editor = dynamic(
  () => import('react-draft-wysiwyg').then((mod) => mod.Editor),
  { ssr: false }
)
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const TextEditor = () => {
  return (
    <>
      <div className="container my-5">
        <Editor
          toolbarClassName="toolbarClassName"
          wrapperClassName="wrapperClassName"
          editorClassName="editorClassName"
        />
      </div>
    </>
  )
}

export default TextEditor

Comments

2

Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload

import React, { Component } from 'react'
import { EditorState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html'; 
import dynamic from 'next/dynamic';
const Editor = dynamic(
() => import('react-draft-wysiwyg').then(mod => mod.Editor),
{ ssr: false })  

import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";


export default class ArticleEditor extends Component {

constructor(props) {
    super(props);

    this.state = {
        editorState: EditorState.createEmpty()
    };
}

onEditorStateChange = (editorState) => {
    this.setState({
        editorState,
    });
    this.props.handleContent(
        convertToRaw(editorState.getCurrentContent()
    ));
};

  uploadImageCallBack = async (file) => {
    const imgData = await apiClient.uploadInlineImageForArticle(file);
    return Promise.resolve({ data: { 
      link: `${process.env.NEXT_PUBLIC_API_URL}${imgData[0].formats.small.url}`
    }});
  }

render() {
    const { editorState } = this.state;
    return (
        <>
            <Editor
                editorState={editorState}
                toolbarClassName="toolbar-class"
                wrapperClassName="wrapper-class"
                editorClassName="editor-class"
                onEditorStateChange={this.onEditorStateChange}
                toolbar={{
                    options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded', 'emoji', 'image', 'history'],
                    inline: { inDropdown: true },
                    list: { inDropdown: true },
                    textAlign: { inDropdown: true },
                    link: { inDropdown: true },
                    history: { inDropdown: true },
                    image: {
                        urlEnabled: true,
                        uploadEnabled: true,
                        uploadCallback: this.uploadImageCallBack,
                        previewImage: true,
                        alt: { present: false, mandatory: false }
                    },
                }}
            />
            <textarea
                disabled
                value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
            />
        </>
    )
}

}

1 Comment

Any Dropdown not working with next.js.
0

I hope this helps

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

const Editor = dynamic<EditorProps>(
  async () => {
    const mod = await import('react-draft-wysiwyg');
    return { default: mod.Editor as unknown as ComponentType<EditorProps> };
  },
  { ssr: false }
);
https://stackoverflow.com/questions/63451068/window-is-not-defined-react-draft-wysiwyg-used-with-next-js-ssr#

Comments

-1

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}
    </>
  )

1 Comment

the problem does not happen when the component is loaded, but when the component is imported.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.