Skip to content

Commit ab61a13

Browse files
elyobotimdorr
authored andcommitted
Allow a router prop to take priority over context prop. (remix-run#3729)
withRouter should allow a router prop specified on a wrapped component to be used instead of the router in context; this pattern is more flexible, avoids overwriting explicitly set tests, and makes testing components wrapped by withRouter more simple.
1 parent 8aa5434 commit ab61a13

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

modules/__tests__/withRouter-test.js

+21
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,25 @@ describe('withRouter', function () {
3838
done()
3939
})
4040
})
41+
42+
it('still uses router prop if provided', function (done) {
43+
const Test = withRouter(function (props) {
44+
props.test(props)
45+
return null
46+
})
47+
const router = {
48+
push() {},
49+
replace() {},
50+
go() {},
51+
goBack() {},
52+
goForward() {},
53+
setRouteLeaveHook() {},
54+
isActive() {}
55+
}
56+
const test = function (props) {
57+
expect(props.router).toBe(router)
58+
}
59+
60+
render(<Test router={router} test={test} />, node, done)
61+
})
4162
})

modules/withRouter.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ function getDisplayName(WrappedComponent) {
99
export default function withRouter(WrappedComponent) {
1010
const WithRouter = React.createClass({
1111
contextTypes: { router: routerShape },
12+
propTypes: { router: routerShape },
1213
render() {
13-
return <WrappedComponent {...this.props} router={this.context.router} />
14+
const router = this.props.router || this.context.router
15+
return <WrappedComponent {...this.props} router={router} />
1416
}
1517
})
1618

0 commit comments

Comments
 (0)