My goal is to create a Higher Order Component (HOC) in TypeScript that takes an ErrorBoundary
as input and returns the user's current location to be used within the ErrorBoundary
component.
Here is the ErrorBoundary component:
import React from "react";
interface ErrorBoundaryProps {
fallback: React.ReactNode;
children: React.ReactNode;
location: {
pathname: string;
};
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
state = { hasError: false };
static getDerivedStateFromError(error: Error) {
return { hasError: true };
}
componentDidUpdate(previousProps: ErrorBoundaryProps) {
if (previousProps.location.pathname !== this.props.location.pathname) {
this.setState({ hasError: false });
}
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
export default ErrorBoundary;
And here is the WithRouter HOC:
import { useLocation } from "react-router-dom";
function WithRouter(OriginalComponent: React.ComponentType) {
const NewComponent = (props: any) => {
const location = useLocation();
return <OriginalComponent {...props} location={location} />;
};
return NewComponent;
}
I am encountering issues with the TypeScript compiler and I have tried various solutions without success. In JavaScript, a similar implementation works fine:
import { useLocation } from "react-router-dom";
function WithRouter(OriginalComponent) {
const NewComponent = (props) => {
const location = useLocation();
return <OriginalComponent location={location} {...props} />;
};
return NewComponent;
}
However, I am struggling to convert it to TypeScript.