Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
withRouter: Directly use RouterContext instead of Route. (#6685)
This reduces the nesting introduced by withRouter() quite a bit and makes for an easier warning in case it's used outside <Router/>
  • Loading branch information
StringEpsilon authored and timdorr committed Apr 3, 2019
1 parent 017f692 commit 10d78bb
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 29 deletions.
12 changes: 6 additions & 6 deletions packages/react-router-dom/.size-snapshot.json
Expand Up @@ -14,13 +14,13 @@
}
},
"umd/react-router-dom.js": {
"bundled": 162079,
"minified": 57806,
"gzipped": 16662
"bundled": 162277,
"minified": 57870,
"gzipped": 16689
},
"umd/react-router-dom.min.js": {
"bundled": 97956,
"minified": 34459,
"gzipped": 10224
"bundled": 98089,
"minified": 34473,
"gzipped": 10230
}
}
22 changes: 11 additions & 11 deletions packages/react-router/.size-snapshot.json
@@ -1,26 +1,26 @@
{
"esm/react-router.js": {
"bundled": 23136,
"minified": 13099,
"gzipped": 3654,
"bundled": 23391,
"minified": 13245,
"gzipped": 3676,
"treeshaked": {
"rollup": {
"code": 2267,
"code": 2209,
"import_statements": 465
},
"webpack": {
"code": 3630
"code": 3572
}
}
},
"umd/react-router.js": {
"bundled": 102232,
"minified": 36232,
"gzipped": 11519
"bundled": 102432,
"minified": 36295,
"gzipped": 11538
},
"umd/react-router.min.js": {
"bundled": 63839,
"minified": 22264,
"gzipped": 7893
"bundled": 63974,
"minified": 22277,
"gzipped": 7899
}
}
31 changes: 19 additions & 12 deletions packages/react-router/modules/withRouter.js
@@ -1,30 +1,37 @@
import React from "react";
import PropTypes from "prop-types";
import RouterContext from "./RouterContext";
import hoistStatics from "hoist-non-react-statics";

import Route from "./Route";
import invariant from "tiny-invariant";

/**
* A public higher-order component to access the imperative API
*/
function withRouter(Component) {
const displayName = `withRouter(${Component.displayName || Component.name})`;
const C = props => {
const { wrappedComponentRef, ...remainingProps } = props;

return (
<Route
children={routeComponentProps => (
<Component
{...remainingProps}
{...routeComponentProps}
ref={wrappedComponentRef}
/>
)}
/>
<RouterContext.Consumer>
{context => {
invariant(
context,
`You should not use <${displayName} /> outside a <Router>`
);
return (
<Component
{...remainingProps}
{...context}
ref={wrappedComponentRef}
/>
);
}}
</RouterContext.Consumer>
);
};

C.displayName = `withRouter(${Component.displayName || Component.name})`;
C.displayName = displayName;
C.WrappedComponent = Component;

if (__DEV__) {
Expand Down

0 comments on commit 10d78bb

Please sign in to comment.