2023-11-29 04:47:55 +11:00
|
|
|
import PropTypes from 'prop-types';
|
2023-10-20 04:44:55 +11:00
|
|
|
|
2023-11-29 04:47:55 +11:00
|
|
|
import { __RouterContext } from 'react-router';
|
2023-10-20 04:44:55 +11:00
|
|
|
|
2023-11-29 04:47:55 +11:00
|
|
|
import hoistStatics from 'hoist-non-react-statics';
|
2023-10-20 04:44:55 +11:00
|
|
|
|
|
|
|
export const WithRouterPropTypes = {
|
|
|
|
match: PropTypes.object.isRequired,
|
|
|
|
location: PropTypes.object.isRequired,
|
|
|
|
history: PropTypes.object.isRequired,
|
|
|
|
};
|
|
|
|
|
|
|
|
export const WithOptionalRouterPropTypes = {
|
|
|
|
match: PropTypes.object,
|
|
|
|
location: PropTypes.object,
|
|
|
|
history: PropTypes.object,
|
|
|
|
};
|
|
|
|
|
2023-11-29 04:47:55 +11:00
|
|
|
export interface OptionalRouterProps {
|
|
|
|
ref: unknown;
|
|
|
|
wrappedComponentRef: unknown;
|
|
|
|
}
|
|
|
|
|
2023-10-20 04:44:55 +11:00
|
|
|
// This is copied from https://github.com/remix-run/react-router/blob/v5.3.4/packages/react-router/modules/withRouter.js
|
|
|
|
// but does not fail if called outside of a React Router context
|
2023-11-29 04:47:55 +11:00
|
|
|
export function withOptionalRouter<
|
|
|
|
ComponentType extends React.ComponentType<OptionalRouterProps>,
|
|
|
|
>(Component: ComponentType) {
|
|
|
|
const displayName = `withRouter(${Component.displayName ?? Component.name})`;
|
|
|
|
const C = (props: React.ComponentProps<ComponentType>) => {
|
2023-10-20 04:44:55 +11:00
|
|
|
const { wrappedComponentRef, ...remainingProps } = props;
|
|
|
|
|
|
|
|
return (
|
|
|
|
<__RouterContext.Consumer>
|
2023-11-29 04:47:55 +11:00
|
|
|
{(context) => {
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
|
|
if (context) {
|
2023-10-20 04:44:55 +11:00
|
|
|
return (
|
2023-11-29 04:47:55 +11:00
|
|
|
// @ts-expect-error - Dynamic covariant generic components are tough to type.
|
2023-10-20 04:44:55 +11:00
|
|
|
<Component
|
|
|
|
{...remainingProps}
|
|
|
|
{...context}
|
|
|
|
ref={wrappedComponentRef}
|
|
|
|
/>
|
|
|
|
);
|
2023-11-29 04:47:55 +11:00
|
|
|
} else {
|
|
|
|
// @ts-expect-error - Dynamic covariant generic components are tough to type.
|
|
|
|
return <Component {...remainingProps} ref={wrappedComponentRef} />;
|
|
|
|
}
|
2023-10-20 04:44:55 +11:00
|
|
|
}}
|
|
|
|
</__RouterContext.Consumer>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
C.displayName = displayName;
|
|
|
|
C.WrappedComponent = Component;
|
|
|
|
C.propTypes = {
|
2023-10-23 20:39:53 +11:00
|
|
|
...Component.propTypes,
|
2023-10-20 04:44:55 +11:00
|
|
|
wrappedComponentRef: PropTypes.oneOfType([
|
|
|
|
PropTypes.string,
|
|
|
|
PropTypes.func,
|
2023-11-29 04:47:55 +11:00
|
|
|
PropTypes.object,
|
|
|
|
]),
|
2023-10-20 04:44:55 +11:00
|
|
|
};
|
|
|
|
|
|
|
|
return hoistStatics(C, Component);
|
|
|
|
}
|