fix: HashHistory Link hrefs escape the hash router - #9
Open
jligeza wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
With
HashHistory,<Link>renders an anchor whosehrefis the plain route-space path (e.g./posts/123) instead of the hash form (#/posts/123).Plain left-clicks still work because
Link'sonClickintercepts them and routes throughrouter.navigate, which goes throughHashHistory.push(the only place that prepends#). But native browser link actions — Ctrl/Cmd-click, middle-click, "copy link address", "open in new tab" — use thehrefdirectly and bypass the click handler. On a static host (e.g. GitHub/GitLab Pages) the browser then requests/posts/123from the server, which doesn't exist, so the link is broken.The root cause is that the mapping from an internal URL to a real browser URL lives only inside each history's
push.Linkhas no read-only way to ask the history "what href should this URL render as", so it falls back to the raw path.Fix
Add an optional
createHref(url)toHistoryLike:BrowserHistory/MemoryHistory: identity (url => url)HashHistory`: `url => `#${url}`Linknow setshref: router.history.createHref?.(url) ?? url.navigatestill pushes the plainurl, andHashHistory.pushstill adds the single#, so there is no double-#.createHrefis optional on the interface, so existing customHistoryLikeimplementations keep working (they fall back to identity).BrowserHistory/MemoryHistoryhrefs are byte-for-byte unchanged.Verification
Rendering a real
<Link to="/posts/123">through a realHashHistoryrouter withreact-dom/server:Before:
<a href="/posts/123">After:
<a href="#/posts/123">BrowserHistory.createHref('/posts/123')→/posts/123(unchanged),HashHistory.createHref('/posts/123')→#/posts/123.