First, please look at the following demo code:
function AComponent() {
return (
<div style={{ width: '150px', border: '1px solid red' }} onClick={() => { console.log('container 1 called'); }}>
<div style={{ width: '100px', border: '1px solid blue' }} onClick={() => { console.log('container 2 called'); }}>
<p style={{ fontSize: '16px', width: '75px', border: '1px solid teal' }}>
this is a text.
</p>
</div>
</div>
);
}
the P
tag has no event attached, though, on the console there will be written:
container 2 called
container 1 called
I think, even I attach an event or not, for every HTML element, all possible events for that element are attached by default.
In react-native, the scenario is different. There are no such things like this.
Actually, I want to
- disable the mentioned behavior of Default Event Attachment.
- disable Event Bubble For every Event by default.
is it possible in react?
Thanks in advance.
2
Answers
I don’t think that there’s any way to disable event bubbling completely by default.
What you can do is to stop event bubbling using
e.stopPropagation()
on the second onClick action.Maybe you can implement a HOF(Higher Order Function) for yourself which get’s a callback action, and inside that HOF you can use
e.stopPropagation()
and then call your passed callback.in this way you can use it everywhere in your code without repeating it.
I am correct, what you want is that the onClick of the p tag should not call their parent elements.
This can be done in react using the stopPropagation method, which stops the bubbling up to the parent elements of event calls.
Example –
Thank you
Hope this helped 🙂