Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

497
Visualizações
How to get mouse X position of a mouse event of a div (and not of its children) with React 17?

I have a simple snippet where I attach a onMouseMove listener to a given div:

<div onMouseMove={handleMouseMove}>
    <div>A</div>
    <div>B</div>
    <div>C</div>
</div>

I want to know the X position of the mouse pointer within the parent div where I attached the mouse listener to. However, the event seems to only contain references to the children divs (as target), and the root (as currentTarget).

The event's nativeEvent property also is not helping it seems.

I'm on React 17. I think this is making it harder as previously the currentTarget would point to that div where I placed the listener to, but on React 17 these listeners to the root.

How can I get the coordinates within the div I attached the listener to?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This works as expected in react version 17.0.2

function Component() {
  const onMouseMove = (e) => {
    let rect = e.currentTarget.getBoundingClientRect();
    let x = e.clientX - rect.left;
    let y = e.clientY - rect.top;

    console.log(x, y);
  };
  return (
    <div onMouseMove={onMouseMove}>
      <div>A</div>
      <div>B</div>
      <div>C</div>
    </div>
  );
}

Based on this answer and a comment on it, about using a currentTarget

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda