stephenscaff / react-animated-cursor

An animated custom cursor React component.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error: ReferenceError: window is not defined

angeldevildev opened this issue · comments

Hi! I was using your react-animated-cursor library everything went well I was able to put the cursor in the website, however it gives me an error that would be:

  • error node_modules\react-animated-cursor\dist\index.js (43:30) @ useEventListener
  • error ReferenceError: window is not defined
    null
    I am developing this website in Next.js.
    I hope you can help me as soon as possible.
    Thank you.

issues-react-pointer

This is a very DOM-reliant FE/client component, that uses UseState, UseEffect, it's not a server side component.
Next (and React) now have this notion of Client and Server Side components.
With FE/Client components you have to add 'use client' atop your file.

https://nextjs.org/docs/app/building-your-application/rendering/client-components
https://react.dev/reference/react/use-client

Not sure how this impacts 3rd party components. Will research right now and report back.

Perhaps i just need to define as a Client Component?

Mentioned this in another of your issues, but i pushed a new version with "use client" defined. Getting "Window is not defined" warnings in server console.

You can prevent this by following the next.js dynamic import method included in docs, the only difference is that you still need to define "use client", so a move could be to create a local component, dynamically import in that with "use client" defined.

For example, create components/Cursor

'use client'

import dynamic from 'next/dynamic';

const AnimatedCursor = dynamic(() => import('react-animated-cursor'), {
    ssr: false,
});

export default function Cursor() {
  return <AnimatedCursor/>
}

Then import that in your app or layout file. That seems to work without any warnings.

Researching different approaches right now.

Note that is isolated to Next. Integrated with Vite and Parcel builds without issue. So, def related to Next's SSR and server components as default architecture.

Give the above approach a go and let me know how it goes.

Hey.

Just released 2.10.1, which includes a rewrite of useEventListener hook, as well as some other stuff, to be more next/ssr/client component friendly.

Now, you shouldn't have to use Next's Dynamic Import anymore. A simple import should work without issue.

Just spun up a fresh Next build, using app directory, and was able to import in the layout.tsx without errors or warnings.

Gonna close this for now, but open back up if you have any issues.

Thanks!