Skip to content

Instantly share code, notes, and snippets.

@meetzaveri
Created September 12, 2018 08:23
Show Gist options
  • Save meetzaveri/8222d4fe0fc42bdfe6de7de6d74785c6 to your computer and use it in GitHub Desktop.
Save meetzaveri/8222d4fe0fc42bdfe6de7de6d74785c6 to your computer and use it in GitHub Desktop.

This is the best error boundary HOC found so far

import React from 'react'
import PropTypes from 'prop-types'

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props)
        this.state = { hasError: false }
    }

    componentDidCatch(error, info) {
        // Display fallback UI
        this.setState({ hasError: true })
        // You can also log the error to an error reporting service
        // Remove this if you have no error logging
        logErrorToMyService(error, info)
    }

    render() {
        const { children, errorMessage } = this.props
        if (this.state.hasError) {
            // You can render any custom fallback UI
            return <h1>{errorMessage}</h1>
        }
        return {children}
    }
}

ErrorBoundary.defaultProps = {
    errorMessage: 'Something went wrong.'
}

ErrorBoundary.propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.node),
        PropTypes.node
    ]).isRequired,
    errorMessage: PropTypes.string
}

export default ErrorBoundary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment