0

I have the following two components with thier respective onClick() handlers. Problem is doSomethingElse is never getting and directly doSomething is getting called.

<ParentComponent onClick={this.doSomething}>
   <ChildComponent onClick={this.doSomethingElse} />
</Parent>

Child is shown as like proover on parent using z-index.

class Parent extends React.Component {
  constructor(props) {
    super(props);

  }

  handleP = (e) => {
    alert("parent")
  };

  render() {
    return (

      <div onClick={this.handleP} style={{
        left: 100,
        top: 100,
        zIndex: 100,
        position: 'absolute',
      }}>
      Parent Text
        <Child  />
      </div>          

    )
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);

  }

  handleC = (e) => {
    alert("child")
  };

  render() {
    return (

      <div onClick={this.handleC} style={{
        left: 1,
        top: 1,
        zIndex: 1000,
        position: 'absolute',
      }}>
      Child Text  
      </div>          

    )
  }
}



React.render(
  <Parent />,
  document.getElementById('react_example')
); 

Jsbin

Sandip Pingle
  • 647
  • 2
  • 14
  • 37

1 Answers1

0

@SandipPingle the issue is because, by default a click event bubbles till window. So after the child handler is invoked the event bubbles to parent component. For that you need to stop the event propogation. Refer to this question and this sandbox for a sample fixed version based on this answer :)

Leela Venkatesh K
  • 1,390
  • 1
  • 13
  • 26