javascript – How to find out the coordinates of the clicked element in react? Relative to parent element

Question:

How to find out the coordinates of the element being clicked relative to the parent element?

Answer:

Method 1: Event target

import React from 'react';

class MyComponent extends React.Component {
    onClick = (e) => {
        const parent = e.target.parentNode.getBoundingClientRect();
        const element = e.target.getBoundingClientRect();

        const x = element.left - parent.left;
        const y = element.top - parent.top;

        console.log(x, y);
    };      

    render() {
        return (
            <div>
                DIV1

                <div onClick={this.onClick}>
                    DIV2
                <div>
            </div>
        );
    }
}

Method 2: refs https://facebook.github.io/react/docs/refs-and-the-dom.html

import React from 'react';

class MyComponent extends React.Component {
    parentRef = React.createRef();
    elementRef = React.createRef();

    onClick = (e) => {
        const parent = parentRef.current.getBoundingClientRect();
        const element = elementRef.current.getBoundingClientRect();

        const x = element.left - parent.left;
        const y = element.top - parent.top;

        console.log(x, y);
    };      

    render() {
        return (
            <div ref={this.parentRef}>
                DIV1

                <div ref={this.currentRef} onClick={this.onClick}>
                    DIV2
                <div>
            </div>
        );
    }
}
Scroll to Top