// withErrorBoundary.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class ErrorBoundary extends Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
componentDidCatch(error, info) {
this.setState({ hasError: true })
console.group('componentDidCatch')
console.error(error)
console.info(info)
console.groupEnd('componentDidCatch')
}
render() {
if (this.state.hasError) {
return <h1>An Error Occurred 😢</h1>
}
return this.props.children
}
}
export default Component => props => (
<ErrorBoundary>
<Component {...props} />
</ErrorBoundary>
)
Easy to Use with ES7 decorator... @withErrorBoundary
// App.js
import withErrorBoundary from './withErrorBoundary.js'
@withErrorBoundary
export default class App extends Component {
simulateError = () => {
throw new Error('Sample Error')
}
render() {
return (
<div>
<h1 onClick={this.simulateError}>Hello World</h1>
</div>
)
}
}
Top comments (1)
Registered on this resource just to say thank you!
I've modified your example so decorator would accept options like this
@withErrorBoundary({ componentName: ' . . . ' })
and we could handle errors in uglified/minified production build
For anyone wondering - the wrapper will look like this
Then ErrorBoundary component will receive options object as a prop (obviously)
Thanks for sharing!