Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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

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

}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

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

useEffect(() => {
  const event = (e) => {
    setMouse({ top: `${e.clientY - 25}px`, left: `${e.clientX - 25}px` 
  }
  document.addEventListener("click", event);
  });
  return () => document.removeEventListener("click", event)
}, [])

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.

It would also be best to add your event listener on component mount, and remove it when the component unmounts with useEffect and the cleanup function.

about 4 years ago · Juan Pablo Isaza Denunciar

0

In order to rerender the component you need to make use of the state. Declare your top and left variable in state like below and add the enent listener once your component is mounted.

import { useEffect, useState } from 'react';

const PlayArea = () => {
    const [state, setState] = useState({
        left: 'inherit',
        top: 'inherit',
    });

    useEffect(() => {
        document.addEventListener('click', (e) => {
            setState({ left: `${e.clientX - 25}px`, top: `${e.clientY - 25}px` });
        });
    }, []);

    return (
        <>
            <div className="ball" style={{ transform: `top ${state.top}, left ${state.left}` }} />
        </>
    );
};

export default PlayArea;

As you are adding your event listener to the document object you need to have the position: fixed unless you have a relative class for the div you have created.

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

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda