Daniel Calderon Mori
Daniel Calderon Mori

Reputation: 5776

React - how to capture only parent's onClick event and not children

I have part of a React Component that looks like this:

var headerElement = someBoolean ? <input/> : 'some string';
return <th onClick={this._onHeaderClick}>{headerElement}</th>;

And a click handler for the th element:

_onHeaderClick(event) {
    event.preventDefault();
    console.log(event.target);
},

I want to capture the th element. It works fine when headerElement is 'some string', but when it is an input element, the input element is the one referenced in the event.target property.

What's the best way to achieve this?

Upvotes: 63

Views: 59381

Answers (5)

Harley Lang
Harley Lang

Reputation: 2333

For some reason the accepted solution did not work for me.

One possible work-around is to add a data-value tag to the child element you wish to exclude from the onClick event:


const eg = () => {

    const clickParent = (event: React.MouseEvent) => {

        event.preventDefault();
        let dataValue = (event.target as HTMLElement).getAttribute('data-value');
        if (dataValue !== 'child') {
            console.log('parent clicked');
        };

    };

    const clickChild = (event: React.MouseEvent) => console.log('child clicked');

    return (

        <div data-value='parent' onClick={clickParent}>

            <div data-value='child' onClick={clickChild}>
            </div>

        </div>

    );


};

Upvotes: 4

Sabir Hussain
Sabir Hussain

Reputation: 2922

simply use event.currentTarget

 onClick(e) {
    e.preventDefault();
    console.log(e.currentTarget);
}

Upvotes: 2

Nghiệp
Nghiệp

Reputation: 4718

Check them

_onHeaderClick(event) {
   event.preventDefault();
   if(event.target === event.currentTarget) {
      // handle
   }
}

Upvotes: 54

Arun P Johny
Arun P Johny

Reputation: 388316

Since you are binding the handler to th you can use the currentTarget property. The target property refers to the element which dispatched the event.

_onHeaderClick(event) {
    event.preventDefault();
    console.log(event.currentTarget);
}

Upvotes: 119

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Like this?

event.target.parentNode

Upvotes: 8

Related Questions