-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact-error-boundary.js
More file actions
42 lines (32 loc) · 1012 Bytes
/
react-error-boundary.js
File metadata and controls
42 lines (32 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import React from 'react';
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error("Error caught by Error Boundary:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong: {this.state.error.message}</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
// usecase
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
const MyComponent = () => {
// Component logic here. For demonstration, we'll keep it simple.
return <div>MyComponent content</div>;
};
const App = () => {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
};
export default App;