Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

don't call function if a nested element was clicked

I have a component with a nested component, like this:

<div id="bla" onClick={() => this.handleOnClick(this.props.someParameter, this.state.someState, {id})}>
    <div class="wrapper">
    <ChildComponent />
    </div>
    ....

The nested component is technically an icon and it has it's own handleOnClick function.

If I click the child component icon both handleOnClick functions are called. But I want to call only the child component's function. Is there a way to do this?

like image 378
Lammi Avatar asked Sep 03 '26 23:09

Lammi


2 Answers

You should use event#stopPropagation.

On your child component's handleOnClick function, just call it like:

handleOnClick = function(e) {
    e.stopPropagation();
    ...rest of your code
} 

I haven't worked with react, but this should work.

like image 113
dquijada Avatar answered Sep 05 '26 13:09

dquijada


Using event.stopPropagation(); in your child component's onClick function will solve your problem.

This method will prevent the event from propagating to your parent component

childOnClick = event => {
    event.stopPropagation();
    //.... your code
}
like image 28
Treycos Avatar answered Sep 05 '26 12:09

Treycos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!