skip to Main Content

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.

2

Answers



  1. The issue you are facing is because NextJS does server side render, the window object only works with client side rendering. Try make the following adjustment in your window object code:

    if (typeof window !== ‘undefined’) {
    // Perform client-side actions here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search