0

I'm working in this example in react.js

<Card onClick="(e)=>{e.preventDefault(); goPage()}">
  <Card.body>
   <Media>
     <img
         width={64}
         height={64}
         className="mr-3"
         src="https://via.placeholder.com/150"
         alt="Generic placeholder"
     />
     <Media.Body>
        <h5>Media Heading</h5>
        <p>
          Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque
          ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at,
          tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla.
          Donec lacinia congue felis in faucibus.
        </p>
        <a href="#/" onClick="(e)=>{e.preventDefault(); downloadPage()}">Download Page</a>
      </Media.Body>
    </Media>
  </Card.body
</Card

But I need to both function's onclick work's independently, if I click in link Download Page I want only work it downloadPage() but not run goPage() and vice versa, is it possible?

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
aloredo
  • 93
  • 5

3 Answers3

3

You're looking for the event.stopPropagation() method to be applied on the <a> tag: MDN: Event.stopPropagation to prevent event bubbling. If you want to learn more, read about event bubbling and capturing at: What is event bubbling and capturing?

83C10
  • 1,112
  • 11
  • 19
2

You can use stopPropagation here is working sample with html:

   function downloadPage() {
            console.log('downloadPage');
        }
   function goPage() {
            console.log('goPage');
        }
    <div onclick="goPage(); event.stopPropagation();">
        goPage
        <div>
            <a href="#/" onclick="downloadPage(); event.stopPropagation();">Download Page</a>
        </div>
    </div>
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
0

It looks like you might want to use stopPropagation instead of preventDefault, and this should onlly be necessary on the tag, so it would look something like this:

<Card onClick={(e)=>{goPage()}}>
<a href="#/" onClick={(e)=>{e.preventDefault(); downloadPage()}}>

Notice I replaced the quotes with curly braces as that's the syntax I'm familiar with and found here, it may or may not work for you

graem
  • 65
  • 1
  • 7