From 05dbeff4733f3f6bf180ceb0d00012e8d86649f5 Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Sat, 23 Apr 2022 01:42:42 -0400 Subject: [PATCH] Fix hashbang route handling for react-router --- src/components/HistoryRouter.tsx | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/components/HistoryRouter.tsx b/src/components/HistoryRouter.tsx index d789944e03..9b0e64f60a 100644 --- a/src/components/HistoryRouter.tsx +++ b/src/components/HistoryRouter.tsx @@ -1,5 +1,8 @@ import React, { useLayoutEffect } from 'react'; import { HistoryRouterProps, Router } from 'react-router-dom'; +import { Update } from 'history'; + +const normalizePath = (pathname: string) => pathname.replace(/^!/, ''); export function HistoryRouter({ basename, children, history }: HistoryRouterProps) { const [state, setState] = React.useState({ @@ -7,14 +10,27 @@ export function HistoryRouter({ basename, children, history }: HistoryRouterProp location: history.location }); - useLayoutEffect(() => history.listen(setState), [history]); + useLayoutEffect(() => { + const onHistoryChange = (update: Update) => { + if (update.location.pathname.startsWith('!')) { + history.replace(normalizePath(update.location.pathname), update.location.state); + } else { + setState(update); + } + }; + + history.listen(onHistoryChange); + }, [ history ]); return (