Ask Your Question
3

How can the react-error-boundary be used to catch errors occurring in an inner component?

asked 2021-10-24 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-27 21:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-24 11:00:00 +0000

Seen: 7 times

Last updated: Feb 27 '22