larrymyers / react-mini-router

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

Ability to prevent default from React's `onClick` Handler #51

Closed hayesgm closed 6 years ago

hayesgm commented 8 years ago

I am looking to make a link that has an href, but that href is ignored via a preventDefault, e.g.

<a href="/account" onClick={this.visitAccount}>My Account</a>

This is generally for users / SEO to know where a link will navigate to. However, the visitAccount() function can perform some logic and possibly decide not to navigate to /account for one reason or another. Currently, it's not possible to prevent this navigation in react-mini-router.

I know this sounds like an esoteric use case, but part of JavaScript is the ability to control exact user flows, and I am currently being blocked by not being able to preventDefault on a navigation via react's onClick() handler for react-mini-router.

I wanted to see if anyone had some insights on how to have an <a> element that can prevent the default navigation behavior or react-mini-router. I am currently solving this by adding a fork that checks for a stopNavigation property on the evt object after the setTimeout() in handleClick() but this may not be the rest solution. I would be happy to check for defaultPrevented but this is always called by handleClick()

Happy for any feedback / to drop a pull request for my patch.

larrymyers commented 8 years ago

Couple of options:

  1. Move the "decide not to navigate" logic in visitAccount() into the route handler assigned to "/account". If you don't want the user to view the components associated with that route, you could redirect with a navigate() call.
  2. Make the "My Account" link a span/button without the href to avoid the handleClick() logic (people could ctrl+click to get around your validation logic anyway when it's an anchor with href attr).

If neither of those work for you I'll happily review a pull request and see if I can get your stopNavigation behavior integrated without making it a breaking change.