Home > Back-end >  React/JS mouse event handlers not working like I would expect it
React/JS mouse event handlers not working like I would expect it

Time:10-20

Lets say I have an app like:

  return (
    <div className="App">
      <button
        onm ouseDown={(e) => console.log("down")}
        onm ouseUp={(e) => console.log("up")}
        onm ouseMove={(e) => console.log("move")}
      >
        test
      </button>
    </div>
  );
}

export default App;

With this minimal example I would expect that down is fired only once when pressing the mousebutton, up also once etc. But my console output shows that things seem to get messy when also moving the mouse? What is going on here? like real input is mousedown->mousemove->mouseup but console is sth like mousedown->mousemove->mouseup->mousedown->mousemove->mouseup which makes no sense to me....

Thanks a lot!

it does not matter if it's an button or not (I just choose a button for simplicity).

CodePudding user response:

Try this:

const handleEvent = (e) => {
        if (e.type === "mousedown") {
            console.log('mouse down')
        } else if (e.type === "mouseup") {
            console.log('mouse up')
        } else if (e.type === "mouseleave") {
            console.log('mouse leave')

        }
return (<div>
                           <button
                            onm ouseLeave={(e)=> handleEvent(e)}
                            onm ouseMove={(e)=> handleEvent(e)}
                            onm ouseUp={(e)=> handleEvent(e)}
                            onm ouseDown={(e)=> handleEvent(e)}>
                               test
                            </button>
</div>

CodePudding user response:

LOL! I can't believe it... I changed my mouse and now it works!

Seems like my wireless mouse somehow lost connection which triggered a mouseup and when the connection was there again a mousedown again...

4 hours of headache! :D

  • Related