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

JavascriptDomReactjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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);
}

Solution 2 - Javascript

Check them

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

Solution 3 - Javascript

Like this?

event.target.parentNode

Solution 4 - Javascript

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>

    );


};

Solution 5 - Javascript

simply use event.currentTarget

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel Calderon MoriView Question on Stackoverflow
Solution 1 - JavascriptArun P JohnyView Answer on Stackoverflow
Solution 2 - JavascriptnghiepitView Answer on Stackoverflow
Solution 3 - JavascriptBhojendra RauniyarView Answer on Stackoverflow
Solution 4 - JavascriptHarley LangView Answer on Stackoverflow
Solution 5 - JavascriptSabir HussainView Answer on Stackoverflow