How to implement error boundaries in React?

by herminia_bruen , in category: Javascript , a year ago

How to implement error boundaries in React?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a year ago

@herminia_bruen 

To implement error boundaries in React, follow these steps:

  1. Create a new component that will serve as the error boundary. This component should extend the React.Component class.
 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. Wrap any section of your React component tree that you want to be covered by the error boundary inside the
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.