-
Notifications
You must be signed in to change notification settings - Fork 28k
/
Copy pathwith-router.tsx
41 lines (36 loc) · 1.16 KB
/
with-router.tsx
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
import React, { type JSX } from 'react'
import type {
BaseContext,
NextComponentType,
NextPageContext,
} from '../shared/lib/utils'
import type { NextRouter } from './router'
import { useRouter } from './router'
export type WithRouterProps = {
router: NextRouter
}
export type ExcludeRouterProps<P> = Pick<
P,
Exclude<keyof P, keyof WithRouterProps>
>
export default function withRouter<
P extends WithRouterProps,
C extends BaseContext = NextPageContext,
>(
ComposedComponent: NextComponentType<C, any, P>
): React.ComponentType<ExcludeRouterProps<P>> {
function WithRouterWrapper(props: any): JSX.Element {
return <ComposedComponent router={useRouter()} {...props} />
}
WithRouterWrapper.getInitialProps = ComposedComponent.getInitialProps
// This is needed to allow checking for custom getInitialProps in _app
;(WithRouterWrapper as any).origGetInitialProps = (
ComposedComponent as any
).origGetInitialProps
if (process.env.NODE_ENV !== 'production') {
const name =
ComposedComponent.displayName || ComposedComponent.name || 'Unknown'
WithRouterWrapper.displayName = `withRouter(${name})`
}
return WithRouterWrapper
}