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:

import React from 'react';

function Cursor() {
    return <span></span>;
}

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', (e) => {
    cursor.setAttribute(
        'style',
        'top: ' + (e.pageY - 10) + 'px; left: ' + (e.pageX - 10) + 'px;'
    );
});

document.addEventListener('click', () => {
    cursor.classList.add('expand');

    setTimeout(() => {
        cursor.classList.remove('expand');
    }, 500);
});

export default Cursor;

App.js

import Cursor from './components/cursor';
    <div className="cursor">
        <Cursor />      
    </div>

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.

useEffect(() => {
   // declare your cursor variable here
}, []);

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