@herminia_bruen
To implement error boundaries in React, follow these steps:
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 |
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can also log the error to an error reporting service console.log(error, errorInfo); } render() { if (this.state.hasError) { // Render fallback UI return <h1>Something went wrong.</h1>; } // Render children as normal return this.props.children; } } |
1 2 3 |
<ErrorBoundary> <MyComponent /> </ErrorBoundary> |
Now, if an error occurs inside the MyComponent
component or any of its child components, the error boundary will catch the error and display the fallback UI specified in the render()
method.
Note: Error boundaries do not catch errors inside event handlers or during rendering. They only catch errors in the component hierarchy below them.