Aung Thiha Aung Thiha - 2 months ago 37
React JSX Question

onClick of both child and parent triggered when child is clicked

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

this.handleChild = this.handleChild.bind(this);
this.handleParent = this.handleParent.bind(this);
}

render() {
return (
<div
style={{width: '100%', height: '500px', background: 'white'}}
onClick={this.handleParent}>

<div
style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}}
onClick={this.handleChild}>
hello
</div>

</div>
);
}

handleParent(e) {
console.log('parent');
}

handleChild(e) {
console.log('child');
}
}


output when child is clicked

child
parent


desire output is

child


I mean I just want to trigger only child's onClick when child is clicked.

Parent is working fine. It triggers only parent's onClick when parent is clicked.
The problem I'm having is with child.

Answer

You need stop propagation inside child handler,

handleChild(e) {
  e.stopPropagation();
  console.log('child');
}

stopPropagation - Prevents further propagation of the current event in the capturing and bubbling phases.

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

    this.handleChild = this.handleChild.bind(this);
    this.handleParent = this.handleParent.bind(this);
  }

  render() {
    return (
      <div
        style={{width: '100%', height: '500px', background: 'white'}}
        onClick={this.handleParent}>

        <div
          style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}}
          onClick={this.handleChild}>
          hello
        </div>

      </div>
    );
  }

  handleParent(e) {
    console.log('parent');
  }

  handleChild(e) {
    e.stopPropagation();
    console.log('child');
  }
}

ReactDOM.render(<Sample />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>