kitze / mobx-router

A simple router for MobX + React apps
509 stars 66 forks source link

Back-button style go back #3

Open peterbe opened 8 years ago

peterbe commented 8 years ago

There are times when, in one component, I know for certainty that the user came from another component. And in the component they're in now I want to have a <a>Go back</a> link. But I want to make the HTML be right-clickable.

This sort of works:

/* This is in the search result component, links back to the search resultS */
<Link view={views.search} params={{q: store.search_term_used}} store={store}>Go Back</Link>

It gets rendered out to:

<a href="/search/Search+Term+Used">Go Back</a>

But when you click that, it loads the page as a "new page" (not like a brand new browser request, it still has the onClick from mobx-router) and doesn't remember where you have scrolled down to.

If instead, I click the browser back button, it all looks the same except my browser knows how far down I was scrolled.

This sort of works:

/* This is in the search result component, links back to the search resultS */
<a href="#" onClick={(e) => this.goBack(e)}>Go Back</a>

And in that handler I can call regular history.back().

However, I now lack the nice href="..." that would make that Go Back link right-clickable.

I tried this:

/* This is in the search result component, links back to the search resultS */
<Link view={views.search} params={{q: store.search_term_used}} store={store}
  onClick={this.goBack}>Go Back</Link>

but it doesn't trigger "my" onclick but instead that of mobx-router.

Another, less desirable option is to do this:

/* This is in the search result component, links back to the search resultS */
let routeUrl = `/search/${store.search_term_used}`
<a href={routeUrl) onClick={(e) => this.goBack(e)}>Go Back</a>

...but I'd love to use something out of mobx-router to get that URL instead of having to create it as a string myself.

kitze commented 8 years ago

Yeah, the component doesn't support a custom onClick handler because that didn't make sense to me. I understand the problem that you have thanks to your detailed explanation!

If I keep "previousView" in the router store, this would be really easy to solve. I can add a "goBack={true}" prop to the component that will always take you back to the view that you came from.

Would this solve your issue?

peterbe commented 8 years ago

If I keep "previousView" in the router store, this would be really easy to solve. I can add a "goBack={true}" prop to the component that will always take you back to the view that you came from.

Yes please!

kitze commented 8 years ago

@peterbe I'll tackle this tomorrow.