1 | import React from "react";
|
2 | import PropTypes from "prop-types";
|
3 | import hoistStatics from "hoist-non-react-statics";
|
4 | import invariant from "tiny-invariant";
|
5 |
|
6 | import RouterContext from "./RouterContext.js";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | function withRouter(Component) {
|
12 | const displayName = `withRouter(${Component.displayName || Component.name})`;
|
13 | const C = props => {
|
14 | const { wrappedComponentRef, ...remainingProps } = props;
|
15 |
|
16 | return (
|
17 | <RouterContext.Consumer>
|
18 | {context => {
|
19 | invariant(
|
20 | context,
|
21 | `You should not use <${displayName} /> outside a <Router>`
|
22 | );
|
23 | return (
|
24 | <Component
|
25 | {...remainingProps}
|
26 | {...context}
|
27 | ref={wrappedComponentRef}
|
28 | />
|
29 | );
|
30 | }}
|
31 | </RouterContext.Consumer>
|
32 | );
|
33 | };
|
34 |
|
35 | C.displayName = displayName;
|
36 | C.WrappedComponent = Component;
|
37 |
|
38 | if (__DEV__) {
|
39 | C.propTypes = {
|
40 | wrappedComponentRef: PropTypes.oneOfType([
|
41 | PropTypes.string,
|
42 | PropTypes.func,
|
43 | PropTypes.object
|
44 | ])
|
45 | };
|
46 | }
|
47 |
|
48 | return hoistStatics(C, Component);
|
49 | }
|
50 |
|
51 | export default withRouter;
|