skip to Main Content

I have a list of movie items where each item is wrapped in a react-router-dom Link component that navigates to a movie details page. Inside each movie item, I have a "Watch Now" button that opens the corresponding movie trailer in a new browser tab.

The issue I’m facing is that when I click the "Watch Now" button, the trailer opens in a new tab as expected, but the parent Link is also activated, leading the current tab to navigate to the movie details page. My goal is to only open the movie details page when areas outside of the "Watch Now" button are clicked.

I have tried using event.stopPropagation() in the onClick handler for the "Watch Now" button to prevent the event from bubbling up to the parent Link, but this hasn’t worked as I expected. The parent Link is still activated whenever I click the "Watch Now" button

Here’s a simplified version of the code I’m using:

<Link to={`/MovieDetail/${movie.id}`}>
    {/* Other elements */}
    <button
        onClick={(e) => {
            e.stopPropagation();
            window.open(`https://www.youtube.com/watch?v=${trailers[index]}`, '_blank');
        }}
    >
        Watch Now
    </button>
    {/* Other elements */}
</Link>

2

Answers


  1. Although you’re using stopPropagation() to prevent the event from bubbling up to the parent Link component, it won’t work as expected because the Link component is still capturing the click event before the button element has a chance to stop the propagation.

    Try this:

    <Link to={`/MovieDetail/${movie.id}`}>
      {/* Other elements */}
      <div onClick={(e) => e.stopPropagation()}>
        <button
          onClick={() =>
            window.open(`https://www.youtube.com/watch?v=${trailers[index]}`, '_blank')
          }
        >
          Watch Now
        </button>
      </div>
      {/* Other elements */}
    </Link>
    
    Login or Signup to reply.
  2. Don’t use the onClick function in the link component. The Link component is still capturing the click event before the button has a chance to stop the propagation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search