Ask Your Question

Revision history [back]

React Error Boundary is a higher-order component that catches JavaScript errors anywhere in their child component tree and logs them. Here's how you can use it to catch errors occurring in an inner component:

  1. First, create an error boundary component that will be responsible for catching errors from its child components.
import React, { Component } from 'react';

class ErrorBoundary extends Component {
  state = {
    hasError: false,
    error: null,
    info: null
  };

  componentDidCatch(error, info) {
    this.setState({ hasError: true, error, info });
  }

  render() {
    const { hasError, error, info } = this.state;

    if (hasError) {
      return (
        <div>
          <h2>Something went wrong.</h2>
          <p>{error.toString()}</p>
          <p>{info.componentStack}</p>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
  1. Wrap the inner component that you want to catch errors for inside the ErrorBoundary component.
import React from 'react';
import ErrorBoundary from './ErrorBoundary';

function MyComponent() {
  // code for MyComponent
}

function App() {
  return (
    <ErrorBoundary>
      <MyComponent />
    </ErrorBoundary>
  );
}

export default App;

Now, any error thrown by the MyComponent will be caught by the ErrorBoundary and displayed as an error message.