2

My Setup

I am using react router 4 in my application and am trying to achieve something along the lines of adding hashes to certain routes on pages, that will save the state of the page so user can link to said state.

So for example - I have products I am listing that have many variants, when the user selects a variant, I add a hash + the variant ID to the URL, so like myapp.com/cars/truck turns to myapp.com/cars/truck#red, this allows users to link to that specific variant, which is what I want.

My problem

My problem arises when the user navigates to a page and selects a few variants, then tries to navigate backward. Because I change the hash, each back step hits the previous variant in the browsers history. So if

  1. the user lands on home myapp.com/
  2. navigates to myapp.com/cars/truck
  3. then selects the red variant => myapp.com/cars/truck#red,
  4. then blue myapp.com/cars/truck#red => myapp.com/cars/truck#blue

When they press the back button on the browser they will go back to myapp.com/cars/truck#red, when the desired effect is they go back to the previous page omitting the variant and hash changes, which would be myapp.com/.

I understand this is the browsers behavior, but what I am wondering is if there is a way to let users link directly to the variant links, and also have it so pressing the back button after the described scenario takes the user back to the previous page (in that scenario it's myapp.com/). Perhaps re-thinking how I am doing this, I am open to any suggestions.

I am using react (16) and react router (v4) for this if this helps. Happy to show any code if needed, please let me know. Thanks for reading!

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133
  • Why don't you not change the hash and change the query params instead then? `myapp.com/cars/truck?color=red&engine=4L&rating=4` – Dominic Nov 06 '17 at 15:50
  • @DominicTobias don't those save in the browser history just the same? – ajmajmajma Nov 06 '17 at 15:55
  • 1
    Ah I misread the question, in that case looks like a dupe of https://stackoverflow.com/questions/20937280/how-to-change-url-without-changing-browser-history (tl;dr use `replaceState`) – Dominic Nov 06 '17 at 15:58
  • 1
    @DominicTobias Yes! that's exactly what I was looking for, if you want to answer I will mark as correct. Thanks so much! – ajmajmajma Nov 06 '17 at 16:13
  • Hah, thanks, why not ;) – Dominic Nov 06 '17 at 16:16

1 Answers1

2

Try replaceState, it will update the URL without adding a history entry:

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.

e.g.

history.replaceState(null, 'Red Truck', '/truck#red')
Dominic
  • 62,658
  • 20
  • 139
  • 163