Home > Enterprise >  addEventListener on React.js
addEventListener on React.js

Time:07-20

I'm trying to run an addEventListener function on a React app, but most of the times it doesn't run as expected.

Not sure if I need to remake it or if its missing something. If so, can you guys help me with that?

const light = document.querySelector('.light');
const grid  = document.querySelector('.grid-container, .navbar, #hex-grid');
  if (light){
      grid.addEventListener('mousemove', function (e) {
      light.style.left = `${e.clientX}px`;
      light.style.top = `${e.clientY}px`;
    });
  };

CodePudding user response:

the line in the code const grid = document.querySelector('.grid-container, .navbar, #hex-grid'); is wrong.if you need to access many element in the jquery you have to querySelectorAll(); function. execute below code,

let grids= document.querySelectorAll("'.grid-container, .navbar, #hex-grid');

Then you can use JavaScript map function add event listener by looping through the nodes array in the grid variable.

grids.map(grid=>(

  grid.addEventListener('mousemove', function (e) {
      light.style.left = `${e.clientX}px`;
      light.style.top = `${e.clientY}px`;
    });

));

I didnt add the const light = document.querySelector('.light'); since you mentioned the logic and what you need too do using light class node. I only referring the the bug in your code.

CodePudding user response:

I changed to querySelector the whole app div ('.App'). Seems to work fine.

  • Related