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?
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>