1
votes

I have developed the onclick functionality which performs specific operation regardless of clicks of tags, it seems like when I click on child tag or child click event fires its relevant parent click event automatically fired.

Need to prevent the event or handle event related to a specific tag is clicked.

What I want is when parent tag is clicked then only parent onclick function should fire, in case of child tag is clicked then only a child's onclick event should be fired.

The same functionality developed using the react app(reactjs) but the result is the same, can not able to handle the onclick event separately.

<div onClick="console.log('div tag click event fired')">
  <h1 onClick="console.log('h1 tag click event fired')">This is a Heading</h1>
  <p onClick="console.log('p tag click event fired')">This is a paragraph.</p>
<div>
2
This is what event bubbling is. You need event.stopPropagation(). Here is more info : medium.com/@vsvaibhav2016/…Shubham Verma
@ShubhamVerma I have tried this but seems like its not worked in react application, can you provide more information or sample live example with the reactjs.ankitkanojia
here is the sample exampleuday
@uday great, this is what i want. Thank you so much for providing such an example. Thank you so much.ankitkanojia

2 Answers

1
votes

using Event stop propagation keeps the event from bubbling any further up into the DOM. here is sample

1
votes

use event.stopPropogation() to prevent event from bubbling to parent.

<div onClick="console.log('div tag click event fired')">
        <h1  onClick="console.log('h1 clicked');event.stopPropagation();">This is a Heading</h1>
        <p onClick="console.log('p tag click event fired'); event.stopPropagation();">This is a paragraph.</p>
    <div>

with react it's slightly different from vanilla js, you can check it here:https://reactjs.org/docs/handling-events.html