Is there a way to prevent Gatsby from refreshing a page when clicking an <a> element without an href?

Viewed 326

I'm attempting to create a donation page on an existing Gatsby site. The 3rd-party donation form script generates, among other things, a text button to choose an alternative payment method. While other interactive elements are buttons and function as expected, this one is an element without an href. When clicking the link, instead of the plugin's modal appearing as expected, the page refreshes as Gatsby tries to route using the tag. Is there a way to prevent Gatsby for imposing any sort of router functionality on the generated link?

My first attempt had been to use gatsby-browser.js with onPreRouteUpdate, something like

export const onPreRouteUpdate = ({ location, prevLocation }) => {
  if (location.pathname === 'donate' && prevLocation === 'donate') {
    return;
  }
}

But actually can't get any lifecycle methods that I've found yet to react to the link click. How can I get Gatsby to just mind its p's and q's about the specific link or really any empty href or # tag? Thanks in advance for any insights people might have!

1 Answers

As far as I can see Gatsby uses jsx which probably trans-compiles from babel (meaning that the website is dynamically set up with a virtual dom i.e React)

There are two approaches. Inject JS into the Web App once it running or solve it internally before React trans-compiles the virtual dom

What you would want to do is grab the button by Id and override its default behavior

export const onPreRouteUpdate = ({ location, prevLocation }) => {
      if (location.pathname === 'donate' && prevLocation === 'donate') {
        return;
      }
    }

This scrip[t will definitely try to route you to the "donate" page

you might want to route the page to its current location

Here is an article on how to do that Routing to the current page in gatsby

The other thing you might want to do is remove the event listener completely here is an example I did to remove a window Keypress Event

Adjust it for your code

 return () => { window.removeEventListener('keydown', onKeyDown) }
Related