-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathIonReactMemoryRouter.tsx
More file actions
56 lines (47 loc) · 2 KB
/
IonReactMemoryRouter.tsx
File metadata and controls
56 lines (47 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* `IonReactMemoryRouter` provides a way to use `react-router` in
* environments where a traditional browser history (like `BrowserRouter`)
* isn't available or desirable.
*/
import type { Action as HistoryAction, Location as HistoryLocation } from 'history';
import type { PropsWithChildren } from 'react';
import React, { useEffect, useRef } from 'react';
import type { MemoryRouterProps } from 'react-router';
import { MemoryRouter, useLocation, useNavigationType } from 'react-router';
import { IonRouter } from './IonRouter';
const RouterContent = ({ children }: PropsWithChildren<{}>) => {
const location = useLocation();
const navigationType = useNavigationType();
const historyListenHandler = useRef<(location: HistoryLocation, action: HistoryAction) => void>();
const registerHistoryListener = (cb: (location: HistoryLocation, action: HistoryAction) => void) => {
historyListenHandler.current = cb;
};
/**
* Processes navigation changes within the application.
*
* Its purpose is to relay the current `location` and the associated
* `action` ('PUSH', 'POP', or 'REPLACE') to any registered listeners,
* primarily for `IonRouter` to manage Ionic-specific UI updates and
* navigation stack behavior.
*
* @param location The current browser history location object.
* @param action The type of navigation action ('PUSH', 'POP', or
* 'REPLACE').
*/
const handleHistoryChange = (location: HistoryLocation, action: HistoryAction) => {
if (historyListenHandler.current) {
historyListenHandler.current(location, action);
}
};
useEffect(() => {
handleHistoryChange(location, navigationType);
}, [location, navigationType]);
return <IonRouter registerHistoryListener={registerHistoryListener}>{children}</IonRouter>;
};
export const IonReactMemoryRouter = ({ children, ...routerProps }: PropsWithChildren<MemoryRouterProps>) => {
return (
<MemoryRouter {...routerProps}>
<RouterContent>{children}</RouterContent>
</MemoryRouter>
);
};