larrymyers / react-mini-router

A minimal URL router for React.js
MIT License
282 stars 38 forks source link

Add a way to stop navigation via React onClick handler #52

Closed hayesgm closed 7 years ago

hayesgm commented 8 years ago

This is a simple patch to allow a React onClick handler to prevent React Mini Router from navigating after a click to an anchor tag. Here's an example of how this works:

function handleClick(e) {
  // Don't navigate unless user prop is set
  if (this.props.user === null) {
    e.nativeEvent.stopNavigation = true
  }
}

<a href="/user" onClick={handleClick} />

The core reason for this is that for many applications, we want to ensure the link structure is correct for bots. But oftentimes, I still want to include logic surrounding what to do when there's a click. This may be to prevent the click, or to call out to our analytics system before navigating away from the screen.

I won't be offended if we think this doesn't belong in this project. There does not seem to be another good way of handling this (e.g. via after the navigation, or through hacks such as setting the target attribute). Happy for all feedback here.

larrymyers commented 7 years ago

" or to call out to our analytics system before navigating away from the screen"

I'd suggest using something like this instead:

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

The RouterMixin will ignore any links that are part of the list of urls it was constructed with, so this is outside of the original intent of the library.