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
This Pen doesn't use any external CSS resources.