2019-03-23 23:00:46 +01:00
|
|
|
import React from 'react'
|
2019-01-14 15:41:09 +01:00
|
|
|
import PropTypes from 'prop-types'
|
2019-05-06 23:42:04 +02:00
|
|
|
import { NextComponentType, NextPageContext } from 'next-server/dist/lib/utils'
|
2019-04-26 09:37:57 +02:00
|
|
|
import { PublicRouterInstance } from './router';
|
2017-08-30 16:07:12 +02:00
|
|
|
|
2019-04-23 00:32:10 +02:00
|
|
|
export type WithRouterProps = {
|
2019-04-26 09:37:57 +02:00
|
|
|
router: PublicRouterInstance,
|
2019-04-23 00:32:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export type ExcludeRouterProps<P> = Pick<P, Exclude<keyof P, keyof WithRouterProps>>
|
|
|
|
|
2019-05-06 23:42:04 +02:00
|
|
|
export default function withRouter<P extends WithRouterProps, C = NextPageContext>(
|
|
|
|
ComposedComponent: NextComponentType<C, any, P>,
|
|
|
|
): React.ComponentClass<ExcludeRouterProps<P>> {
|
2019-04-23 00:32:10 +02:00
|
|
|
class WithRouteWrapper extends React.Component<ExcludeRouterProps<P>> {
|
2019-04-13 13:21:28 +02:00
|
|
|
static displayName?: string
|
2019-03-23 23:00:46 +01:00
|
|
|
static getInitialProps?: any
|
2019-01-14 15:41:09 +01:00
|
|
|
static contextTypes = {
|
2019-03-23 23:00:46 +01:00
|
|
|
router: PropTypes.object,
|
2019-01-14 15:41:09 +01:00
|
|
|
}
|
|
|
|
|
2019-04-23 00:32:10 +02:00
|
|
|
context!: WithRouterProps
|
|
|
|
|
2019-03-23 23:00:46 +01:00
|
|
|
render() {
|
2019-01-14 15:41:09 +01:00
|
|
|
return <ComposedComponent
|
|
|
|
router={this.context.router}
|
2019-04-23 00:32:10 +02:00
|
|
|
{...this.props as any}
|
2019-01-14 15:41:09 +01:00
|
|
|
/>
|
|
|
|
}
|
|
|
|
}
|
2019-01-11 16:04:56 +01:00
|
|
|
|
2019-03-23 21:31:44 +01:00
|
|
|
WithRouteWrapper.getInitialProps = ComposedComponent.getInitialProps
|
2019-04-13 13:21:28 +02:00
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
const name = ComposedComponent.displayName || ComposedComponent.name || 'Unknown'
|
|
|
|
WithRouteWrapper.displayName = `withRouter(${name})`
|
|
|
|
}
|
2019-03-23 21:31:44 +01:00
|
|
|
|
|
|
|
return WithRouteWrapper
|
2017-08-30 16:07:12 +02:00
|
|
|
}
|