React: event bubbling through nested components

React supports Synthetic Events across it’s Virtual DOM in both capturing and bubbling phases (as described here: https://facebook.github.io/react/docs/events.html).

This means that you could put an onClick handler on any DOM element near the root and it should trigger for all Click events on the page:

<root>
  <div onClick={this.handleAllClickEvents}>
    <comp1>
      <comp2>
        <target>
          <div id={this.props.id}>click me</div>

However, since it will fire for all click events, you would need to disambiguate between them in the click handler (which makes for some pretty ugly code).

function handleAllClickEvents(event) {
  var target = event.relatedTarget;
  var targetId = target.id;
  switch(targetId) {
    case 'myBtn1':
      // handle myBtn1 click event
    case 'myBtn2':
      // handle myBtn2 click event
  }
}

This style of Event Delegation is actually what React does under the hood (https://shripadk.github.io/react/docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation) so you have to ask yourself if that’s what you really want to do.

Alternatively you might want to look at something like the Dispatcher pattern in Flux (https://reactjs.org/blog/2014/07/30/flux-actions-and-the-dispatcher.html). It’s a little bit more complicated to get going but it’s a better solution overall.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)