You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.0 KiB
68 lines
2.0 KiB
12 months ago
|
import PropTypes from 'prop-types';
|
||
1 year ago
|
|
||
12 months ago
|
import { __RouterContext } from 'react-router';
|
||
1 year ago
|
|
||
12 months ago
|
import hoistStatics from 'hoist-non-react-statics';
|
||
1 year ago
|
|
||
|
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,
|
||
|
};
|
||
|
|
||
12 months ago
|
export interface OptionalRouterProps {
|
||
|
ref: unknown;
|
||
|
wrappedComponentRef: unknown;
|
||
|
}
|
||
|
|
||
1 year ago
|
// 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
|
||
12 months ago
|
export function withOptionalRouter<
|
||
|
ComponentType extends React.ComponentType<OptionalRouterProps>,
|
||
|
>(Component: ComponentType) {
|
||
|
const displayName = `withRouter(${Component.displayName ?? Component.name})`;
|
||
|
const C = (props: React.ComponentProps<ComponentType>) => {
|
||
1 year ago
|
const { wrappedComponentRef, ...remainingProps } = props;
|
||
|
|
||
|
return (
|
||
|
<__RouterContext.Consumer>
|
||
12 months ago
|
{(context) => {
|
||
|
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||
|
if (context) {
|
||
1 year ago
|
return (
|
||
12 months ago
|
// @ts-expect-error - Dynamic covariant generic components are tough to type.
|
||
1 year ago
|
<Component
|
||
|
{...remainingProps}
|
||
|
{...context}
|
||
|
ref={wrappedComponentRef}
|
||
|
/>
|
||
|
);
|
||
12 months ago
|
} else {
|
||
|
// @ts-expect-error - Dynamic covariant generic components are tough to type.
|
||
|
return <Component {...remainingProps} ref={wrappedComponentRef} />;
|
||
|
}
|
||
1 year ago
|
}}
|
||
|
</__RouterContext.Consumer>
|
||
|
);
|
||
|
};
|
||
|
|
||
|
C.displayName = displayName;
|
||
|
C.WrappedComponent = Component;
|
||
|
C.propTypes = {
|
||
1 year ago
|
...Component.propTypes,
|
||
1 year ago
|
wrappedComponentRef: PropTypes.oneOfType([
|
||
|
PropTypes.string,
|
||
|
PropTypes.func,
|
||
12 months ago
|
PropTypes.object,
|
||
|
]),
|
||
1 year ago
|
};
|
||
|
|
||
|
return hoistStatics(C, Component);
|
||
|
}
|