Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

394
Views
how to add event listener to determine what the coordinates inside a div is clicked?

Suppose that I have div box that is 200px by 500px.

The objective is to add an event listener to determine the x and y coordinates inside of this div that is clicked.

How can that be down in React?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use getBoundingClientRect() to get the position of the element, plus MouseEvent.clientX and MouseEvent.clientY to get the click coordinate.

See demo:

function XYComponent() {
  const go = (e) => {
    const offsets = e.target.getBoundingClientRect();
    const y = e.clientY - offsets.top;
    const x = e.clientX - offsets.left;
    console.log(x, y);
  }
  return (
    <div>
      <div class="demo" onClick={go}>AAA</div>
      <div class="demo" onClick={go}>BBB</div>
    </div>
  )
}

ReactDOM.render(<XYComponent />, document.querySelector("#app"))
body {
  font-family: monospace;
}
.demo {
  border: 1px solid black;
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!