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?
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.
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.
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.
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); }
Check them
_onHeaderClick(event) { event.preventDefault(); if(event.target === event.currentTarget) { // handle } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With