Home > Blockchain >  Create a yellow circle on mousemove with react
Create a yellow circle on mousemove with react

Time:05-23

I am trying to create a circle cursor on mousemove with react, but nothing is happening. This is the component where I track the mouse movements:

  import React, { useState, useEffect } from "react";

  function Cursor() {
  const [x, setX] = useState(0);
  const [y, setY] = useState(0);

  const logMousePosition = (e) => {
    setX(e.clientX);
    setY(e.clientY);

    e.target.setAttribute("style", "top: "   y   "px; left: "   x   "px;");

  };

  useEffect(() => {

    document.addEventListener("mousemove", logMousePosition);
  }, []);

  return <span></span>;
}

export default Cursor;

CodePudding user response:

Set up an event handler to have it re run the function each time there is a change

import React, { useState, useEffect } from "react";

  function Cursor() {
  const [x, setX] = useState(0);
  const [y, setY] = useState(0);

  const logMousePosition = (e) => {
    setX(e.clientX);
    setY(e.clientY);

    e.target.setAttribute("style", "top: "   y   "px; left: "   x   "px;");

  };

  useEffect(() => {

    return () => { document.addEventListener("mousemove", logMousePosition)
}; }, []);
    
  

return <span></span>;
}

export default Cursor;

CodePudding user response:

It's working now. I changed this line:

e.target.setAttribute("style", "top: "   y   "px; left: "   x   "px;");

into:

e.target.setAttribute("style", "top: "   e.clientY   "px; left: "   e.clientX   "px;");

I guess it's because now it's calculating the position of the mouse dynamically on every render. If anyone has a better explanation I'd appreciate it.

  • Related