Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to get the mouse position in a React Component?

Tags:

reactjs

I have a component that renders a canvas element. I have an onMouseMove handler, but when I move my mouse towards the top of the element event.clientY prints 86. Why not 0? Is there an synthetic event property that will give me the point relative to the element's coordinate system and not the windows?

like image 564
Alex Bollbach Avatar asked Nov 15 '25 19:11

Alex Bollbach


1 Answers

You can use targets offsetTop to get relative position by subtracting from clientY like

event.clientY - event.target.offsetTop

You can see the example

class App extends React.Component{
  render(){
    return(
      <div>
        <div>Top Component</div>
        <div className="main" onMouseMove={(e) => console.log(e.clientY - e.target.offsetTop)}>Main Component</div>
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById("root"));
div{
  min-height: 50px;
}

div.main{
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
like image 189
Jyothi Babu Araja Avatar answered Nov 17 '25 08:11

Jyothi Babu Araja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!