Kevin Danikowski
Kevin Danikowski

Reputation: 5176

stop parent onClick when child is clicked (React or vanilla JS)

I have a sticky bar that I would like to let users close out by having an X in the right side with position: absolute. However, when clicked, it also fires off the "Share to Facebook" event. How do I stop this from happening?

enter image description here

JS File

return (
    <div
      className={'ShareBar'}
      onClick={()=>console.log('sharing')}>
        <span className={'ShareCTA'}>
          {facebook.svg} Share on Facebook &trade;
          <span
            className={'CloseButton'}
            handleClick={function (e) { e.stopPropagation()/*attempted fix*/; console.log('closing'); return; }}>
              X
          </span>
        </span>
    </div>
  );

CSS File (it's a sass file so no semicolons and stuff

.ShareBar
  position fixed
  bottom 0
  z-index 9999
  display flex
  justify-content flex-end
  align-items center
  height 48px
  cursor pointer
  width 100%
  ...

  .ShareCTA
    width 100%
    position relative
    display flex
    justify-content center
    align-items center
    font-size 20px
    ...
    svg
      height 20px

  .CloseButton
    position absolute
    z-index 99999
    right 10px
    border-radius 50%
    height 40px
    width 40px
    display flex
    justify-content center
    align-items center
    ...

Upvotes: 3

Views: 2854

Answers (2)

Tholle
Tholle

Reputation: 112777

stopPropagation will work like you have written, but the event handler for click events is called onClick, not handleClick:

<span
  className={'CloseButton'}
  onClick={e => e.stopPropagation()}
>
  X
</span>

Upvotes: 5

Daniel Bernardi
Daniel Bernardi

Reputation: 507

Wrap the Share to Facebook text in a span and attach the onClick handler to that.

You shouldn't nest an element with an onClick inside another with an onClick.

Upvotes: 1

Related Questions