How to implement a Higher Order Component using TypeScript?

38 Views Asked by At

I am trying to implement a Higher Order Component (HOC) in TypeScript so that I can pass my ErrorBoundary as a parameter to the HOC and then the HOC returns the current location of the user so that I can use it in my ErrorBoundary component.

ErrorBoundary:

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;

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;
}

Apparently the TypeScript compiler is not happy and I'm not sure how to fix it. I've just tried to experiment with different implementations but nothing seems to be working.

If this helps, this is what works in JavaScript:

import { useLocation } from "react-router-dom";

function WithRouter(OriginalComponent) {
  const NewComponent = (props) => {
    const location = useLocation();

    return <OriginalComponent location={location} {...props} />;
  };
  return NewComponent;
}

But I'm just struggling to convert it to TypeScript.

0

There are 0 best solutions below