Search code examples
reactjsreact-routerreduxreact-router-redux

How to handle onclicks on hyperlinks most gracefully


What I want is rendered HTML that looks like this <a href="/page/my-cool-slug">My cool Slug</a>.

That means that someone can right-click on the link and open in a new tab. That'll bypass the fancy pushState stuff that react-router provides.

However, if someone makes a regular click, I need to update redux to say what the new slug is (or pagination page or whatever) AND call browserHistory.push(...).

There has to be a simpler way that is convenient. Something that does almost all of this without all the mess. Here's what my application looks like:

// imports
import { browserHistory } from 'react-router'
import changeSlug from './actions'

// the function
makeURL(thing) {
  return `/page/${thing.slug}`
}

// this click method
handleClick(event, thing) {
  event.preventDefault()
  this.props.dispatch(changeSlug(thing.slug))
  browserHistory.push(`/page/${thing.slug}`)
}

// the JSX
<a href={makeURL(myobject)}
  onClick={(event) => handleClick(event, myobject)}
>Go to {myobject.title}</a>

Also, I tried using event.target in the event handler to get to the a.href attribute but because the <a> tag contains <span> elements, then event.target is the <span> tag I clicked inside the <a> element.


Solution

    1. You can use <Link /> from react_router and determine onEnter/etc. actions in your <Route /> (in <Router />).
    2. Also you can wrap your <a> in <span> and add some attributes to it and handle click event.
    3. Also you can add display: block style to <a> => it shouldn't wraps by <span>