All files / lib/ErrorBoundary index.js

63.64% Statements 7/11
12.5% Branches 1/8
33.33% Functions 1/3
63.64% Lines 7/11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                              3x 3x   3x                                 3x                   89x                 89x           89x    
import React from 'react';
import PropTypes from 'prop-types';
 
class ErrorBoundary extends React.Component {
 
  state = { 
    error: null, 
    errorInfo: null
  };
 
  componentDidCatch(error, errorInfo) {
    this.setState({
      error: error,
      errorInfo: errorInfo
    });
 
    if (this.props.errorCallback) {
 
      this.props.errorCallback(error, errorInfo);
    }
  }
 
  render() {
    const { error, errorInfo } = this.state;
    const { children, fallbackComponent } = this.props;
 
    const errorComponent = () =>
      fallbackComponent
      ? React.cloneElement(fallbackComponent, {
          error: error,
          errorInfo: errorInfo
        })
      : (
        <div>
          <h2>Something went wrong.</h2>
          <details style={{ whiteSpace: 'pre-wrap' }}>
            {error && error.toString()}
            <br />
            {errorInfo.componentStack}
          </details>
        </div>
      );
 
    return (
      errorInfo
        ?
        errorComponent()
        :
        children
    );
  }
}
 
ErrorBoundary.propTypes = {
  /** @prop Children nodes to render inside the ErrorBoundary | null */
  children: PropTypes.node,
  /** @prop Callback function invoked when an error has occured | null */
  errorCallback: PropTypes.func,
  /** @prop Sets a backup Component in the case of a failure | null */
  fallbackComponent: PropTypes.node,
};
 
ErrorBoundary.defaultProps = {
  children: null,
  errorCallback: null,
  fallbackComponent: null
};
 
ErrorBoundary.displayName = 'ErrorBoundary';
 
export default ErrorBoundary;