Skip to main content

One post tagged with "error boundary"

View All Tags

· One min read
Kumar Nitesh

A simple example of creating an ErrorBounday component and using in your application.

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) {    // You can also log the error to an error reporting service    logErrorToMyService(error, info);  }
  render() {    if (this.state.hasError) {      // You can render any custom fallback UI      return <h1>Something went wrong.</h1>;    }
    return this.props.children;  }}

To use above component import it in your app or in the component file where you want to use it

import ErrorBoundary from./ErrorBoundary’

and wrap your component with the imported component

<ErrorBoundary>  <Your Component /></ErrorBoundary>