Skip to content

Instantly share code, notes, and snippets.

@baluragala
Created October 10, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baluragala/77d260f457c02ac62d8b1d3641a4582a to your computer and use it in GitHub Desktop.
Save baluragala/77d260f457c02ac62d8b1d3641a4582a to your computer and use it in GitHub Desktop.
React error boundary component
import React, {Component} from 'react';
class TryCatch extends Component {
constructor(props) {
super(props);
/*
initial state. hasError property is used to conditionally render fallback UI.
Please not hasError property name is arbitarily chosen and can be any name of your choice
*/
this.state = {hasError: false};
}
/*
new lifecyle method that will be called by React when error occurs either in render or
any other lifecycle methods
*/
componentDidCatch(error, info) {
// set the state to re-render when there is an error
this.setState({hasError: true});
}
render() {
// check if fallback UI has to be rendered in case of error
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Sorry, an error has occurred, we logged a ticket automatically</h1>;
}
//if you are here then there is no error hence render children
return this.props.children;
}
}
export default TryCatch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment