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