forked from remix-run/react-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwithRouter.js
47 lines (36 loc) · 1.36 KB
/
withRouter.js
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
import invariant from 'invariant'
import React from 'react'
import hoistStatics from 'hoist-non-react-statics'
import { ContextSubscriber } from './ContextUtils'
import { routerShape } from './PropTypes'
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}
export default function withRouter(WrappedComponent, options) {
const withRef = options && options.withRef
const WithRouter = React.createClass({
mixins: [ ContextSubscriber('router') ],
contextTypes: { router: routerShape },
propTypes: { router: routerShape },
getWrappedInstance() {
invariant(
withRef,
'To access the wrapped instance, you need to specify ' +
'`{ withRef: true }` as the second argument of the withRouter() call.'
)
return this.wrappedInstance
},
render() {
const router = this.props.router || this.context.router
const { params, location, routes } = router
const props = { ...this.props, router, params, location, routes }
if (withRef) {
props.ref = (c) => { this.wrappedInstance = c }
}
return <WrappedComponent {...props} />
}
})
WithRouter.displayName = `withRouter(${getDisplayName(WrappedComponent)})`
WithRouter.WrappedComponent = WrappedComponent
return hoistStatics(WithRouter, WrappedComponent)
}