Home > Blockchain >  React (Next.JS) Import Component After Page Loaded
React (Next.JS) Import Component After Page Loaded

Time:03-27

Im using react-owl-carousel package but when i refresh page its throwing an error that says "window is not defined" so thats right. Module trying to access window object before page loaded. I tried to use React.lazy but it not worked and my page throwed another error says reactdomserver does not yet support suspense (I tried to change next.config.js to use it but still throwing that error.)

Question is i need something like this

import OwlCarousel from "react-owl-carousel" //import it just like that right after page loaded (or window object is accesible)

package: https://www.npmjs.com/package/react-owl-carousel

CodePudding user response:

Next.js supports ES2020 dynamic import() for JavaScript. With it you can import JavaScript modules dynamically and work with them. They also work with SSR.

You can import your component dynamicaly and disable server side rendering, this way it will have access to window

Create your component and use there OwlCarousel

import React from 'react';
import OwlCarousel from 'react-owl-carousel';

const OwlComponent = () => {
    return (
        <div>
            <OwlCarousel />
        </div>
    );
};

and now import that component as dynamic one

import dynamic from "next/dynamic";
 
const OwnComponentNoServerRendering = dynamic(() =>
import("../components/OwlComponent"), {   ssr: false });

It should work as a charm

  • Related