Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 778
Daniel Calderon Mori Avatar asked Dec 18 '15 05:12

Daniel Calderon Mori


People also ask

How do you stop event propagation in react?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.

How do you pass event from child component to parent in react?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

What is onClickCapture?

React onClickCapture is an event handler that gets triggered whenever we click on an element. like onclick, but the difference is that onClickCapture acts in the capture phase whereas onClick acts in the bubbling phase i.e. phases of an event.


2 Answers

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); } 
like image 163
Arun P Johny Avatar answered Sep 21 '22 14:09

Arun P Johny


Check them

_onHeaderClick(event) {    event.preventDefault();    if(event.target === event.currentTarget) {       // handle    } } 
like image 22
nghiepit Avatar answered Sep 22 '22 14:09

nghiepit