-1

How can I get this code to work in React/Gatsby. When I go to build it fails

window.addEventListener("mousemove", move);

window.onload = () => animejs({ targets: ".cursor", opacity: 1 });

  • In what way does it fail? Are there errors? And have you checked out the anime.js wrappers for React mentioned [here](https://stackoverflow.com/questions/61951482/how-to-use-animejs-inside-react/61962093)? – Zac Anger Jan 13 '21 at 21:13
  • Please may you provide a runnable [mcve]? Otherwise we're kinda left guessing – evolutionxbox Jan 13 '21 at 21:32

1 Answers1

1

Wrap it inside this condition:

if (typeof window !== "undefined"){
   window.addEventListener("mousemove", move);

   window.onload = () => animejs({ targets: ".cursor", opacity: 1 });

 }

You need to understand Gatsby to know what's going on. As a summary, gatsby develop occurs in the browser-side, where there's a window (or other global objects like document) so your code won't break. gatsby build occurs in the server where obviously there's no window (because it's not even defined yet), so every portion of code that uses window without validation, will break.

Wrapping the code inside the previous condition will make your code work.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67