Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 773
Aung Thiha Avatar asked Sep 13 '16 12:09

Aung Thiha


1 Answers

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>
like image 67
Oleksandr T. Avatar answered Nov 09 '22 22:11

Oleksandr T.