Event Bubbling In React Doesn't Stop Using E.preventdefault()
Solution 1:
So the thing is that when you try to focus on the input by clicking on it, an onClick event is triggered on input and propogated to the parent,
You have two possible solutions:
First: Add an onClick event on the input and stopPropagation of the event.
constApp = () => (
<divstyle={styles}><table><thonClick={()=>alert('fire')}>
name
<inputonClick={(e) => {e.stopPropagation()}} onChange={e=>{alert('change text')}}/>
</th></table></div>
);
or
Second: Check the target
in the onClick
event before taking an action
constApp = () => (
<divstyle={styles}><table><thonClick={(e)=>{if(e.target.id !== 'input') {alert('fire')}}}>
name
<inputid="input"onChange={e=>{alert('change text')}}/>
</th></table></div>
);
Solution 2:
If you only want the th
click handler to fire when it is clicked on directly, you can check the target:
<th onClick={e => {
if (e.currentTarget === e.target) {
alert('fire');
}
}}>
The other option is to add a click handler to the input with a stopPropagation call:
<input onChange={e=>{e.preventDefault();alert('change text')}} onClick={e => e.stopPropagation()}/>
MDN details on currentTarget
:
Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
Post a Comment for "Event Bubbling In React Doesn't Stop Using E.preventdefault()"