Next Js dynamic imports with no SSR not working

Viewed 5518

I'm trying to use this react-carousel-3d library https://github.com/suhailsulu/react-carousel-3d but I'm getting the below error as the library is not developed to support SSR.

`ReferenceError: window is not defined`
at Object.<anonymous> (C:\Deba\Workspace2021\Nextjs\myportfolio\node_modules\3d-react-carousal\dist\index.js:1:255)

Now I'm trying to use dynamic imports with no SSR https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

const {Carousel} = dynamic(
    () => import('../node_modules/3d-react-carousal/src/index.js'),
    { ssr: false }
  )

I'm getting below error now:

./node_modules/3d-react-carousal/src/index.js 189:12
Module parse failed: Unexpected token (189:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
     render() {
        return (
             <div className="react-3d-carousel" style={{ height: this.state.height }}>
                 {this.state.slides && this.state.slides.length > 0 &&
                     <div className="slider-container">

Can somebody point out what i'm doing wrong here or any ideas on how to get this working?

1 Answers

Not sure if you can dynamically load from the node_module, like this:

const {Carousel} = dynamic(
    () => import('3d-react-carousal'),
    { ssr: false }
  )

But you should be able to do this by creating a carousal component first, then dynamic import it like this:

// create a component named MyCarousel.js in components folder
import {Carousel} from '3d-react-carousal';

let slides = [
    <img  src="https://picsum.photos/800/300/?random" alt="1" />,
    <img  src="https://picsum.photos/800/301/?random" alt="2" />  ,
    <img  src="https://picsum.photos/800/302/?random" alt="3" />  ,
    <img  src="https://picsum.photos/800/303/?random" alt="4" />  ,
    <img src="https://picsum.photos/800/304/?random" alt="5" />   ];

const MyCarousel = (<Carousel slides={slides} autoplay={true} interval={1000}/>);
export default MyCarousel;

// then dynamic import it:

const MyCarousel = dynamic(
    () => import('../components/MyCarousel'),
    { ssr: false }
  )
Related