class ErrorBoundary extends React.Component {
state = { error: null }
static getDerivedStateFromError(error) {
return { error }
}
render() {
const { error } = this.state
if (error) {
return <this.props.fallback error={error} />
}
return this.props.children
}
}
const Child = () => {
throw new Error("Something Wrong...")
return <p>Child...</p>
}
const Fallback = ({error}) = {
return <p>{error.message}</p>
}
const App = () => {
return (
<>
<p>App</p>
<ErrorBoundary fallback={Fallback}>
<Child />
</ErrorBoundary>
</>
)
}