How to use dynamic import with a named export in Next.js?

Viewed 870

I have this react component. It works just fine for me.

import { Widget } from 'rasa-webchat';

function CustomWidget(){
    return (
        <Widget
        initPayload={"payload"}
        socketPath={"/socket.io/"}
        customData={{"language": "en"}}
        />
    )
}
export default CustomWidget;

But when I try to use it on my next.js website it fails to work.

It gives me a window is not defined error.

I think I resolved this particular error by using the dynamic importer:

import dynamic from "next/dynamic";

const webchat = dynamic(
  () => {
    return import('rasa-webchat');
  },
  { ssr: false }
);

But now I can't figure out how to actually use the widget component from the package.

Am I allowed to import { Widget } from 'rasa-webchat' or is this just not compatible with next.js for some reason? If it's possible, how do I do it?

2 Answers

Nextjs is a frame work that allows you to build Static and Server Side rendered apps. So, it uses Nodesj under hood and window is not defined in nodejs. Only way to accessing window in react ssr frameworks is useEffect hook. Your dynamic import solution is right , becuase you are getting file on client side. I hope it makes sense.

Have a great day

The syntax for named exports is slightly different. You can use the widget with a dynamic import as follows:

import dynamic from 'next/dynamic';

const Widget = dynamic(
    () => import('rasa-webchat').then((mod) => mod.Widget),
    { ssr: false }
);

function CustomWidget(){
    return (
        <Widget
            initPayload={"payload"}
            socketPath={"/socket.io/"}
            customData={{"language": "en"}}
        />
    )
}

export default CustomWidget;

For further details check Next.js dynamic import documentation.

Related