UNPKG

1.21 kBJavaScriptView Raw
1import React from "react";
2import PropTypes from "prop-types";
3import RouterContext from "./RouterContext";
4import hoistStatics from "hoist-non-react-statics";
5import invariant from "tiny-invariant";
6
7/**
8 * A public higher-order component to access the imperative API
9 */
10function 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
50export default withRouter;