Search code examples
javascriptreactjsreduxevent-bubbling

How can I stop event bubbling for nested components dispatching a redux action?


I dynamically render a bunch of nested components, all of which are also attached to a redux action.

Unfortunately, the action is being called for all of them when I click the inner most element, what can I do to stop it from bubbling under these circumstances?

Example code:

  <div onClick={()=>this.props.anAction(elementName)}>{elementName}
      <div onClick={()=>this.props.anAction(innerElementName)}>{innerElementName}
        <div onClick={()=>this.props.anAction(innerInnerElementName)}>    
            {innerInnerElementName}
        </div>
     </div>
  </div>

Solution

  • You can pass in onClick event and trigger stopPropagation()

    <div onClick={(e)=>this.props.anAction(innerInnerElementName, e)}>    
       {innerInnerElementName}
    </div>
    
    anAction(el, ev) {
      ev.stopPropagation();
      ...
    }