Reputation: 83
I'm trying to integrate a JS library in my NextJS app, but when loading the page I always get the following error on the server-side:
ReferenceError: window is not defined
I don't understand why this occurs, since I'm using this library inside a useEffect hook. Besides that, I'm also reinforcing it by putting a condition on the window object (which shouldn't be needed).
import { Draggable } from "@shopify/draggable";
import { useEffect, useRef } from "react";
type DraggableItemListProps = {
children: React.ReactNode
}
export default function DraggableItemList({children}: DraggableItemListProps) {
const container = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!container.current || typeof window === 'undefined') {
return;
}
const draggable = new Draggable(container.current, {
draggable: '.draggable',
handle: '.draggable-handle'
});
return () => {
draggable.destroy();
}
}, [children])
return (
<div ref={container}>{children}</div>
)
}
If I remove everything inside the useEffect, and I simply use the window object in any way, it works without any issue. Can somebody please tell me what I'm missing?
Thank you.
Upvotes: 0
Views: 51
Reputation: 83
Solved by using dynamic import: https://nextjs.org/learn-pages-router/seo/improve/dynamic-import-components .
Upvotes: 0