rsnext/packages/next/client/with-router.tsx
Luis Fernando Alvarez D b94123ccc9 Improve exported router types (#7853)
* Added the RouteUrl type and improved router types

* Added more tests for router types

* Add build test for typescript types

* Add next-env.d.ts to the typescript test

* Removed next-env.d.ts

* Added next-env.d.ts to gitignore

* Remove route url re-exports

* renamed PublicRouterInstance to be NextRouter

* export the Url type

* Replaced BaseRouter with NextRouter in server/utils

* Don't export the Url type

* Update tsconfig.json
2019-07-11 13:35:39 -04:00

48 lines
1.2 KiB
TypeScript

import React from 'react'
import PropTypes from 'prop-types'
import { NextComponentType, NextPageContext } from 'next-server/dist/lib/utils'
import { NextRouter } 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 = NextPageContext
>(
ComposedComponent: NextComponentType<C, any, P>
): React.ComponentClass<ExcludeRouterProps<P>> {
class WithRouteWrapper extends React.Component<ExcludeRouterProps<P>> {
static displayName?: string
static getInitialProps?: any
static contextTypes = {
router: PropTypes.object,
}
context!: WithRouterProps
render() {
return (
<ComposedComponent
router={this.context.router}
{...this.props as any}
/>
)
}
}
WithRouteWrapper.getInitialProps = ComposedComponent.getInitialProps
if (process.env.NODE_ENV !== 'production') {
const name =
ComposedComponent.displayName || ComposedComponent.name || 'Unknown'
WithRouteWrapper.displayName = `withRouter(${name})`
}
return WithRouteWrapper
}