Removes the Router/Switch/Route/Link/LinkContainer legacy-context
warnings. Keeps the shared history singleton (used outside React by
NotificationsObserver + Utils/location) via unstable_HistoryRouter, and
bridges v6 hooks back to v4-shaped history/match/location props with a
new withRouterCompat HOC so the ~20 class pages stay untouched.
- <Switch> -> <Routes>, component= -> element=
- Authenticated/Public -> guard components (children or <Navigate replace>)
- LocationListener -> useLocation + useEffect function
- regex route /fire/:type(active|archive|alert)/:id -> /fire/:type/:id
- history.listen callback is ({ location }) in history v5
Browser-verified: SPA nav, /subscriptions->/login auth redirect,
deep-link /fire/archive/:id (params), browser back/forward. REST smoke
byte-identical.
33 lines
1.4 KiB
JavaScript
33 lines
1.4 KiB
JavaScript
import React from 'react';
|
|
import { useNavigate, useLocation, useParams } from 'react-router-dom';
|
|
|
|
// react-router v6 dropped the `history`/`match`/`location` props that our ~20
|
|
// class page components still read. Rather than convert every class to hooks,
|
|
// this HOC bridges the v6 hooks back to the v4-shaped props those components
|
|
// expect: `history.push/replace(to, state)`, `match.params`, `match.url`,
|
|
// and `location`. New code should use the hooks directly instead.
|
|
export default function withRouterCompat(Component) {
|
|
function WithRouterCompat(props) {
|
|
const navigate = useNavigate();
|
|
const location = useLocation();
|
|
const params = useParams();
|
|
|
|
const history = {
|
|
push: (to, state) => navigate(to, state !== undefined ? { state } : undefined),
|
|
replace: (to, state) => navigate(to, { replace: true, ...(state !== undefined ? { state } : {}) }),
|
|
goBack: () => navigate(-1),
|
|
goForward: () => navigate(1),
|
|
location
|
|
};
|
|
|
|
// v4 `match.url` was the matched path; for our leaf/exact routes that is
|
|
// simply the current pathname.
|
|
const match = { params, url: location.pathname, path: location.pathname };
|
|
|
|
return <Component {...props} history={history} location={location} match={match} />;
|
|
}
|
|
|
|
const name = Component.displayName || Component.name || 'Component';
|
|
WithRouterCompat.displayName = `withRouterCompat(${name})`;
|
|
return WithRouterCompat;
|
|
}
|