React how to ignore onClick for child element

Viewed 3192

I have a child component inside a parent component. I want to to alert message when I click everywhere inside parent except when clicking on child.

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

Code example here:

http://jsfiddle.net/rgL5f9yh/

2 Answers

Add e.stopPropagation() to child onClick property

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div onClick={(e) => e.stopPropagation()} className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

You can prevent event propagation in the child element i.e

<button onClick={((e) => e.stopPropagation())}>Do not alert On this element click</button>
Related