Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change css in react in this example?

I am trying to move the ball to the point where the mouse clicks. The function is logging the X and Y but not moving the ball. What am I missing here?

Typescript react component

  const PlayArea = () => {
  let top = 'inherit';
  let left = 'inherit';
  
  document.addEventListener("click", function(e){
    console.log((e.clientX + 25) + 'px')
    top = (e.clientY - 25) + "px";
    console.log(top)
    left = e.clientX - 25 + "px";
  });
  return (
    <>
      <div className="ball" style={{ transform: `top ${top}, left ${left}` }}></div>
    </>
  );
};

export default PlayArea;

css

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.ball {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  background-color: #0b8027; 
  position:absolute;

}

>Solution :

Set your top and left variables to state objects and update them on your click event callback.

const [mouse, setMouse] = useState({})

document.addEventListener("click", function(e){
    setMouse({top: `${e.clientY - 25}px`, left: `${e.clientX - 25}px`})
  });

return (
    <>
      <div className="ball" style={{ top: mouse?.top, left: mouse?.left }}></div>
    </>
);

You don’t need to transform your top and left style properties. You set them directly, and the elements position will allow it to move to the location you give it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading