Import html-to-draftjs on Nextjs

Viewed 1154

I unable to import html-to-draftjs on my Nextjs Project. If I import it with:

import htmlToDraft from "html-to-draftjs"

The result will be:

window is not defined

I try to use dynamic import:

const htmlToDraft = dynamic(
  () => {
    return import("html-to-draftjs");
  },
  { ssr: false }
);

The result is: htmlToDraftjs is not a function

Is there any other import method that I can try? or maybe is there any alternative htmltodraft module that i can use? Thank You!

3 Answers

There's 2 other ways, if you use functional components

1st Method:

Downgrade your "html-to-draftjs" package to version 1.4, so you can directly import it, without using the "dyanmic" import method.

2nd Method:

Import the package in this way:

let htmlToDraft = null;
if (typeof window === 'object') {
    htmlToDraft = require('html-to-draftjs').default;
}

A modern syntax solution for one of the previous solutions would look like this:

const htmlToDraft = typeof window === 'object' && require('html-to-draftjs').default;

window object is not available at server. So the error happens on the server. If you only want to run htmlToDraft on browser then you should run it on componentDidMount as I can see you are using class components.

The componentDidMount lifecycle method only execute on client side in Next JS.

The render method is going to execute in both server & client. That's why you get that error. Put that into componentDidMount

Related