Raja Muhammad Asher
Raja Muhammad Asher

Follow

Raja Muhammad Asher

Follow
React ErrorBoundary Component

Photo by Lautaro Andreani on Unsplash

React ErrorBoundary Component

Raja Muhammad Asher's photo
Raja Muhammad Asher
·Mar 11, 2023·

1 min read

In React, an ErrorBoundaryComponent JavaScript errors anywhere in its child component tree and displays a fallback UI instead of crashing the application.

Here's an example:

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, info) {
    // Example "componentStack":
    //   in ComponentThatThrows (created by App)
    //   in ErrorBoundary (created by App)
    //   in div (created by App)
    //   in App
    logErrorToMyService(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return this.props.fallback;
    }

    return this.props.children;
  }
}

Then you can call it as

<ErrorBoundary fallback={<p>Something went wrong</p>}>
  <Profile />
</ErrorBoundary>
 
Share this