Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make withRouter HOC stateful to allow refs #5382

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/react-router/modules/__tests__/withRouter-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,26 @@ describe('withRouter', () => {
expect(ref instanceof WrappedComponent).toBe(true)
})

it('exposes the instance of the wrapper via ref', () => {
class WrappedComponent extends React.Component {
render() {
return null
}
}
const Component = withRouter(WrappedComponent)

let ref
ReactDOM.render((
<MemoryRouter initialEntries={[ '/bubblegum' ]}>
<Route path="/bubblegum" render={() => (
<Component ref={r => ref = r}/>
)}/>
</MemoryRouter>
), node)

expect(ref instanceof Component).toBe(true)
})

it('hoists non-react statics from the wrapped component', () => {
class Component extends React.Component {
static foo() {
Expand Down
28 changes: 16 additions & 12 deletions packages/react-router/modules/withRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,23 @@ import Route from './Route'
* A public higher-order component to access the imperative API
*/
const withRouter = (Component) => {
const C = (props) => {
const { wrappedComponentRef, ...remainingProps } = props
return (
<Route render={routeComponentProps => (
<Component {...remainingProps} {...routeComponentProps} ref={wrappedComponentRef}/>
)}/>
)
}
class C extends React.Component {
static displayName = `withRouter(${Component.displayName || Component.name})`

static WrappedComponent = Component

static propTypes = {
wrappedComponentRef: PropTypes.func
}

C.displayName = `withRouter(${Component.displayName || Component.name})`
C.WrappedComponent = Component
C.propTypes = {
wrappedComponentRef: PropTypes.func
render() {
const { wrappedComponentRef, ...remainingProps } = this.props
return (
<Route render={routeComponentProps => (
<Component {...remainingProps} {...routeComponentProps} ref={wrappedComponentRef}/>
)}/>
)
}
}

return hoistStatics(C, Component)
Expand Down