2019-03-23 23:00:46 +01:00
|
|
|
import React from 'react'
|
2019-09-04 16:00:54 +02:00
|
|
|
import { NextComponentType, NextPageContext } from '../next-server/lib/utils'
|
2019-11-09 23:56:59 +01:00
|
|
|
import { NextRouter, useRouter } from './router'
|
2017-08-30 16:07:12 +02:00
|
|
|
|
2019-04-23 00:32:10 +02:00
|
|
|
export type WithRouterProps = {
|
2019-07-11 19:35:39 +02:00
|
|
|
router: NextRouter
|
2019-04-23 00:32:10 +02:00
|
|
|
}
|
|
|
|
|
2019-05-30 03:19:32 +02:00
|
|
|
export type ExcludeRouterProps<P> = Pick<
|
|
|
|
P,
|
|
|
|
Exclude<keyof P, keyof WithRouterProps>
|
|
|
|
>
|
2019-04-23 00:32:10 +02:00
|
|
|
|
2019-05-30 03:19:32 +02:00
|
|
|
export default function withRouter<
|
|
|
|
P extends WithRouterProps,
|
|
|
|
C = NextPageContext
|
|
|
|
>(
|
|
|
|
ComposedComponent: NextComponentType<C, any, P>
|
2019-11-09 23:56:59 +01:00
|
|
|
): React.ComponentType<ExcludeRouterProps<P>> {
|
|
|
|
function WithRouterWrapper(props: any) {
|
|
|
|
return <ComposedComponent router={useRouter()} {...props} />
|
2019-01-14 15:41:09 +01:00
|
|
|
}
|
2019-01-11 16:04:56 +01:00
|
|
|
|
2019-11-09 23:56:59 +01:00
|
|
|
WithRouterWrapper.getInitialProps = ComposedComponent.getInitialProps
|
2019-09-20 22:49:49 +02:00
|
|
|
// This is needed to allow checking for custom getInitialProps in _app
|
2019-11-09 23:56:59 +01:00
|
|
|
;(WithRouterWrapper as any).origGetInitialProps = (ComposedComponent as any).origGetInitialProps
|
2019-04-13 13:21:28 +02:00
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
2019-05-30 03:19:32 +02:00
|
|
|
const name =
|
|
|
|
ComposedComponent.displayName || ComposedComponent.name || 'Unknown'
|
2019-11-09 23:56:59 +01:00
|
|
|
WithRouterWrapper.displayName = `withRouter(${name})`
|
2019-04-13 13:21:28 +02:00
|
|
|
}
|
2019-03-23 21:31:44 +01:00
|
|
|
|
2019-11-09 23:56:59 +01:00
|
|
|
return WithRouterWrapper
|
2017-08-30 16:07:12 +02:00
|
|
|
}
|