I'm using 'NextJs 13to build a website, in my home I have a slider of my products and I use
tiny-slider-react` to create a slider.
I added use client
in the first line of my carousel.js
file;
carousel.js file code:
"use client";
import TinySlider from "tiny-slider-react";
import CarouselItem from "./carousel-item";
import "tiny-slider/dist/tiny-slider.css";
import { useEffect, useState } from "react";
function Carousel(props) {
const [mount, setMount] = useState(false);
const { children } = props;
useEffect(() => {
if (typeof window === "object") {
setMount(true);
}
}, [setMount, window]);
const settings = {
lazyload: true,
nav: false,
mouseDrag: true,
loop: true,
items: 1,
gutter: 20,
controls: false,
autoplay: true,
autoplayHoverPause: true,
autoplayButtonOutput: false,
speed: 250,
autoplayTimeout: 2500,
responsive: {
2048: {
items: 10,
},
1920: {
items: 4,
},
1728: {
items: 4,
},
1440: {
items: 4,
},
1280: {
items: 4,
},
1194: {
items: 4,
},
1114: {
items: 4,
},
1180: {
items: 4,
},
1104: {
items: 4,
},
1024: {
items: 4,
},
834: {
items: 2,
},
820: {
items: 2,
},
800: {
items: 2,
},
768: {
items: 2,
},
},
};
if (mount) {
return (
<TinySlider settings={settings} onInit={() => {}}>
{props.data.map((item) => (
<CarouselItem key={item.id} data={item} />
))}
</TinySlider>
);
}
return null;
}
export default Carousel;
but every time I reload the page I get this error:
error node_modules\tiny-slider\dist\tiny-slider.js (5:0) @ eval
error ReferenceError: window is not defined
at webpack_require (F:\Projects\nexjs\decoz.next\server\webpack-runtime.js:33:42) at webpack_require (F:\Projects\nexjs\decoz.next\server\webpack-runtime.js:33:42) at webpack_require (F:\Projects\nexjs\decoz.next\server\webpack-runtime.js:33:42) at eval (./components/theme/home/carousel/carousel.js:7:75)
and I can't run 'npm run build` too, it gets this error:
info - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules
How to avoid this error?
package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"aos": "^2.3.4",
"eslint": "8.40.0",
"eslint-config-next": "13.4.1",
"next": "13.4.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"tiny-slider-react": "^0.5.7"
}
}
You are passing window
as a dependency of your useEffect
hook. First of all, it is unnecessary. Second, it causes your error when Next tries to render your component on the server.
You can resolve this error by rewriting your effect as follows.
useEffect(() => {
setMount(true);
}, []);
UPDATE: Another issue here is that tiny-slider-react
is not compatible with SSR as it's referencing window
object directly. You can resolve this error by dynamically importing tiny-slider-react
.
import dynamic from "next/dynamic";
const TinySlider = dynamic(() => import("tiny-slider-react"));