skip to Main Content

I have a card wrapped in a Link from the react-router-dom@v5. Inside the Link is a div for the card and the div is positioned relatively. Inside the card div is an icon positioned absolutely to the card that when clicked should change background color. The problem now is that clicking on the icon also clicks the Link which I don’t want. I tried to use e.preventDefault() but it also stops all subsequent events from firing again properly as I want to be able to flip the background color of the icon any time I click on it. I tried e.stopPropagation() and e.nativeEvent.stopImmediatePropagation but they don’t seem to work.

I have also gone through several SO answers but none seem to fix my problem.


 function handleFavClick(event) {
    event.stopPropagation();
    console.log(event);
 }

 <Link to={`/movies/${movie.id}`} key={movie.id}>

      <div 
        className="card"
        key={movie.id}
      >
        <img 
          src="/heart-icon.png"
          alt="heart icon"
          onClick={handleFavClick}
        />
        <img 
          src="/card-image.png"
          alt="original card image"

        />
      </div>  
 </Link>

What could be the issue?

2

Answers


  1. your code show follow this pattern. Event.preventDefault() works when submitting a form in order to prevent the page from reloading.
    In other not to click on the link tag from react-router-dom, you should remove img tag from the Link tag.

    import { Link } from "react-router-dom"

    const onClickFunction = () =>{

    const handleFavClick = (event) =>{
        event.preventDefault() 
        console.log(event);
     }
    
    return (
      <>
      <Link to={`/movies/${movie.id}`} key={movie.id}>
         <div className="card" key={movie.id}>
         <img src="/card-image.png" alt="original card image"/>
         </div>  
     </Link>
     <img src="/heart-icon.png" alt="heart icon" onClick={handleFavClick}/>
     </>
    );
    

    }

    export default onClickFunction;

    Login or Signup to reply.
  2. To prevent the Link from being triggered when clicking on the heart icon while still allowing the handleFavClick function to execute, you can wrap the Link with a div and place the onClick event handler on that div. This way, clicking the heart icon won’t trigger the Link. Here’s an updated version of your code:

    <div onClick={() => handleFavClick(movie.id)}>
      <Link to={`/movies/${movie.id}`} key={movie.id}>
        <div className="card" key={movie.id}>
          <img src="/heart-icon.png" alt="heart icon" />
          <img src="/card-image.png" alt="original card image" />
        </div>
      </Link>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search