stephenscaff / react-animated-cursor

An animated custom cursor React component.
ISC License
273 stars 28 forks source link

Error: ReferenceError: window is not defined #54

Closed angeldevildev closed 7 months ago

angeldevildev commented 8 months ago

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:

issues-react-pointer

stephenscaff commented 7 months ago

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?

stephenscaff commented 7 months ago

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.

stephenscaff commented 7 months ago

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!