DEV Community

Shun Tedokon
Shun Tedokon

Posted on

Using React ErrorBoundary with HOCs

// 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> ) 
Enter fullscreen mode Exit fullscreen mode

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>  ) } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
olesbolotniuk profile image
oles-bolotniuk • Edited

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

export default options => Component => props => { return ( <ErrorBoundary options={ options }> <Component { ...props } /> </ErrorBoundary> ); }; 

Then ErrorBoundary component will receive options object as a prop (obviously)

Thanks for sharing!