Skip to content
Advertisement

Website crashing due to eventListeners; TypeError: Cannot read property ‘setAttribute’ of null

I’m trying to build and add a custom cursor on my website created using CSS/JS. Everything compiles fine and the webpage loads normally until you move the mouse… even 1 pixel. Upon moving the mouse, the webpage crashes, and I get the TypeError: Cannot read property 'setAttribute' of null error.

cursor.js:

JavaScript

App.js

JavaScript

Advertisement

Answer

The problem here is that the JS code runs before the HTML renders. This means that the cursor variable is not defined. TO solve this I would suggest you use React useEffect hook.

JavaScript

useEffect basically runs the code inside the callback function that’s passed into it when a particular state changes. You can specify which state or states you want it to listen to in the array.

For now I’ve passed it as empty since we’re just waiting for the component HTML to render.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement