EyeBall wont follow onMouseMove event

260 Views Asked by At

I am trying to make an eye that follows the cursor in a web page using react. I have succesfully done it using vanilla HTML,CSS,and JS but is having trouble using React. I have called an event listener for the eyeball using onMouseMove, but it only works if the web page is clicked. Please tell me, what am I doing wrong here.

This is my component:

import React, { Component } from "react";
import "./Eye.css";

class Eye extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    left: 0,
    top: 0,
  };

  componentDidMount() {
    window.addEventListener("mousemove", this._onMouseMove);
  }

  _onMouseMove = (e) => {
    var balls = document.getElementsByClassName("ball");

    console.log(e.nativeEvent);

    var x = (e.clientX * 100) / window.innerWidth + "%";
    var y = (e.clientY * 100) / window.innerHeight + "%";

    balls[0].style.left = x;
    balls[0].style.top = y;
    balls[0].style.transform = "translate(-" + x + ",-" + y + ")";

    this.setState({ left: x, top: y });
  };
  render() {
    return (
      <div className='eyes'>
        <div className='eye'>
          <div className='ball'></div>
        </div>
      </div>
    );
  }
}

export default Eye;

This is my main App.js:

import React, { useState, useEffect } from "react";
import "./App.css";
import Eye from "./components/Eye";

function App() {

  return (
    <div className='App'>
      <Eye onMouseMove={(event) => this.handleMouse(event)} />
    </div>
  );
}

export default App;

UPDATE #1: I didnt realize that eventlisteners doesnot work on inspect mode. Once I exited the inspect mode it works fine. I also have altered the event listener so that the event listener does not eat much memory. However, I think something is still wrong since when I move the mouse. Any help on how to improve this?

0

There are 0 best solutions below