Next.js Stop Propagation on a nested Link element
Asked Answered
W

5

5

I have these tiles that are clickable which while send the user to some external page plus a button inside of the tile that should route the user to some page inside of the site. The problem with this is that when clicking on the button, both events are fired so it sends the user to the external page + navigates to the internal page.

<div
  tabIndex={0}
  role="button"
  onClick={onClick}
>
  <div>
    // some markup
    <Link href={url} passHref>
      <a
        role="button"
        onClick={(e) => sendUserToInternalPageEvent(e)}
      >
        // some text
      </a>
    </Link>
  </div>
</div>

The event for sendUserToInternalPageEvent is using the nextjs event object for the Link component. I'm trying to stop propagation for sendUserToInternalPageEvent but event.stopPropagation() is undefined. The goal is for sendUserToInternalPageEvent to send the user to an internal page while using the nextjs Link element and have onClick send the user to the external page.

Wormeaten answered 3/2, 2021 at 23:42 Comment(2)
question is a bit hard to understand for me, however if you'd like to use event and stopPropagation on anchor using Link, you could try to wrap it, e.g. <div><a ...>...</a></div>Intubate
@Intubate This didn't give me the desired effect as it stopped the other event I needed.Wormeaten
W
6

I ended up going this route

const stopPropagation = (e) => {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  };
<div
  tabIndex={0}
  role="button"
  onClick={onClick}
>
  <div>
    // some markup
    <Link href={url} passHref>
      <a
        role="button"
        onClick={(e) => {
          stopPropagation(e);
          if (!disabled) onClick(e);
        }}
      >
        // some text
      </a>
    </Link>
  </div>
</div>
Wormeaten answered 8/2, 2021 at 20:3 Comment(0)
N
4

For Nextjs 13, you can use e.preventDefault() before your onClick event

Nerland answered 3/3, 2023 at 14:49 Comment(0)
A
0

I would recommend swapping out the link element for a div that has an onClick and uses nextjs' router. For example:

<div onClick={() => router.push("/page")}>
  Content
</div>
  

stopPropagation(e); should then work. Keep in mind that this will remove the autoloading that nextjs normally does for links, which you'll need to re-add yourself.

Advisee answered 8/11, 2022 at 23:35 Comment(0)
Y
0

For me worked a combination of

onClick={(e) => {
   e.stopPropagation();
   e.nativeEvent.preventDefault();
   // your handler
}}
Yemane answered 16/12, 2022 at 14:14 Comment(0)
F
0

To prevent triggering the Link if the button clicked, just add passHref in your Link tag and add the following in your button click listener:

onClick={(evt) => {
   evt.preventDefault();
   evt.nativeEvent.stopImmediatePropagation();
   // your handler
}}
Flanch answered 31/10 at 4:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.