console.clear();

const { useState } = React;

const withErrorHandling = WrappedComponent => {
  return class extends React.Component {
    state = {
      error: null
    };

    static getDerivedStateFromError(error) {
      // Update state so the next render will show the fallback UI.
      return { error };
    }

    render() {
      if (this.state.error) {
        return (
          <details>
            <summary>Ouch! Things are messed up. We are sorry. 👾</summary>
            <pre style={{ color: `red` }}>{this.state.error.stack}</pre>
          </details>
        );
      }
      return <WrappedComponent {...this.props} />;
    }
  };
};

const BadComponent = () => (
  <div>
    <p>This component will not render {new Date()}</p>
  </div>
);

const SafeComponent = withErrorHandling(BadComponent);

const App = () => (
  <>
    <h2>Higher Order Component Example</h2>
    <SafeComponent />
  </>
);

ReactDOM.render(<App />, document.body);
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js