Lammi
Lammi

Reputation: 77

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?

Upvotes: 3

Views: 466

Answers (3)

Ana Liza Pandac
Ana Liza Pandac

Reputation: 4871

In your child component event handler, make sure you stop the event from propagating so it doesn't bubbles up to the parent div by calling event.stopPropagation()

class ChildComponent extends React {

  handleChange(event) {
    event.stopPropagation();
  }

  render() {
    return (
        <div>
        <button onClick={this.handleChange}></button>
       </div>
    );
  }
}

Upvotes: 2

Treycos
Treycos

Reputation: 7492

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
}

Upvotes: 2

dquijada
dquijada

Reputation: 1699

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.

Upvotes: 3

Related Questions