UNPKG

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