Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Created February 24, 2019 04:17
Show Gist options
  • Save jrobinsonc/e0eea5e6e980b24e92eb63486a36e8fe to your computer and use it in GitHub Desktop.
Save jrobinsonc/e0eea5e6e980b24e92eb63486a36e8fe to your computer and use it in GitHub Desktop.
React ErrorBoundary

File ErrorBoundary.js.

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    logToErrorLogger(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <div>Help, something went wrong.</div>;
    }

    return this.props.children; 
  }
}

File MyComponent.js

import ErrorBoundary from './ErrorBoundary';

const ComponentOne = React.lazy(() => import('./ComponentOne'));

function MyComponent() {
   return (
       <ErrorBoundary>
           <React.Suspense fallback={<div>Loading...</div>}>
               <ComponentOne/>
           </React.Suspense>
       </ErrorBoundary>
   );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment