ak5
ak5

Reputation: 53

React: onClick() event provides wrong cursor coordinates

please educate me on the following issue. I have a React component. On mouse button click, I'm getting the cursor position and handle that (use the onClick event).

The issue happens when I mouse-click and then quickly move the cursor. In result, onClick() handler gets an event containing not proper mouse position - not where the click happened, but where the cursor stopped after the quick move.

In addition to onClick(), I have onMouseMove() handler. And on that quick cursor move, multiple onMouseMove events get fired before the onClick event.

Why does this happen? Is this because of the lower priority of the onClick? Then, how to get the position of mouse-click?

Below is a simplified code that demonstrates the issue:

import React from 'react'

export class MyComponent extends React.Component {
    onClick(e) {
        console.log('ON CLICK, clientX:', e.clientX)
    }

    onMouseMove(e) {
        console.log('on move, clientX:', e.clientX)
    }

    render() {
      return (
        <div style={{width: 300, height: 300, backgroundColor: 'blue'}}
           onClick={this.onClick} onMouseMove={this.onMouseMove}/>
      )
    }
  }

Upvotes: 5

Views: 13751

Answers (3)

I followed the steps from the response from Michalis, But I found incorrect values in the event, this is caused probably by React, I've found the way to work around it here's what I've found.

The clientX and clientY are bigger than the width and height of the target element when clicking in the right-bottom corner. See the image example showing the error.enter image description here

Also, there is a problem with this approach with touch devices I created a new sandbox that works for both desktop and touch devices, you can check it out in the link below. Demo

Upvotes: 1

Michalis Garganourakis
Michalis Garganourakis

Reputation: 2930

If you need the value of clientX exactly the moment you press the mouse click, you should use onmousedown (onMouseDown for React) instead.

enter image description here

Here is a working example.


For onclick to be triggered, both mousedown + mouseup(button release) of your left mouse button should occur. Thus, if the mouse is moved in the meantime (while you are still holding the button), your log will end up with the value of your final position.

Upvotes: 6

Ethan Lipkind
Ethan Lipkind

Reputation: 1156

when you "click", are you performing both a "mousedown" and a "mouseup"? in other words, are you releasing the mouse before moving it? the "click" event fires only when both the mousedown and mouseup events have occurred on the div, so if you go mousedown, then move the cursor, then do mouseup, the click will register in the location where you did the mouseup, not the mousedown.

Upvotes: 0

Related Questions