Skip to content

Commit

Permalink
fix: keep hash/fragment section un URLs on web (#11078)
Browse files Browse the repository at this point in the history
**Motivation**

Fixes this issue that I discovered
#11026

**Test plan**

1. Run the example
2. Visit http://localhost:19006/simple-stack/article/gandalf#test
3. The with #test part still exists
4. Note that if you change the hash it will be gone (this is expected)
  • Loading branch information
nikgraf committed Dec 7, 2022
1 parent b3722fd commit 31cb2a2
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions packages/native/src/createMemoryHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,28 @@ export default function createMemoryHistory() {

const id = window.history.state?.id ?? nanoid();

// Need to keep the hash part of the path if there was no previous history entry
// or the previous history entry had the same path
let pathWithHash = path;

if (!items.length || items.findIndex((item) => item.id === id) < 0) {
// There are two scenarios for creating an array with only one history record:
// - When loaded id not found in the items array, this function by default will replace
// the first item. We need to keep only the new updated object, otherwise it will break
// the page when navigating forward in history.
// - This is the first time any state modifications are done
// So we need to push the entry as there's nothing to replace
items = [{ path, state, id }];
pathWithHash = pathWithHash + location.hash;
items = [{ path: pathWithHash, state, id }];
index = 0;
} else {
if (items[index].path === path) {
pathWithHash = pathWithHash + location.hash;
}
items[index] = { path, state, id };
}

window.history.replaceState({ id }, '', path);
window.history.replaceState({ id }, '', pathWithHash);
},

// `history.go(n)` is asynchronous, there are couple of things to keep in mind:
Expand Down

0 comments on commit 31cb2a2

Please sign in to comment.