Skip to content

Commit

Permalink
Adding support to get the component instance that withRouter HOC wraps (
Browse files Browse the repository at this point in the history
#3735)

* More code style fixes

* Fixing code style, and updating ref to be a function ref

* updating error message from not passing in proper options object

* Updating withRouter based on comments

* Reverting change to withRouter

* Last minute spacing issues

* Fixing some spacing issues

* withRouter now supports withRef as an option, to better support getting the wrapped instance
  • Loading branch information
Bigguy34 authored and timdorr committed Aug 19, 2016
1 parent af58641 commit af276b2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
18 changes: 18 additions & 0 deletions modules/__tests__/withRouter-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ describe('withRouter', function () {
propTypes: {
router: routerShape.isRequired
}
testFunction() {
return 'hello from the test function'
}
render() {
expect(this.props.router).toExist()
return <h1>App</h1>
Expand Down Expand Up @@ -59,4 +62,19 @@ describe('withRouter', function () {

render(<Test router={router} test={test} />, node, done)
})

it('should support withRefs as a parameter', function (done) {
const WrappedApp = withRouter(App, { withRef:true })
const router = {
push() {},
replace() {},
go() {},
goBack() {},
goForward() {},
setRouteLeaveHook() {},
isActive() {}
}
const component = render((<WrappedApp router={router}/>), node, done)
expect(component.getWrappedInstance().testFunction()).toEqual('hello from the test function')
})
})
14 changes: 12 additions & 2 deletions modules/withRouter.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
import React from 'react'
import hoistStatics from 'hoist-non-react-statics'
import { routerShape } from './PropTypes'
import warning from './routerWarning'


function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

export default function withRouter(WrappedComponent) {
export default function withRouter(WrappedComponent, options) {
const WithRouter = React.createClass({
contextTypes: { router: routerShape },
propTypes: { router: routerShape },
getWrappedInstance() {
warning(options && options.withRef, 'To access the wrappedInstance you must provide {withRef : true} as the second argument of the withRouter call')
return this._wrappedComponent
},
render() {
const router = this.props.router || this.context.router
return <WrappedComponent {...this.props} router={router} />
if (options && options.withRef) {
return <WrappedComponent {...this.props} ref={(component)=>this._wrappedComponent = component} router={router} />
} else {
return <WrappedComponent {...this.props} router={router} />
}
}
})

Expand Down

0 comments on commit af276b2

Please sign in to comment.