Created
October 10, 2017 17:42
-
-
Save baluragala/77d260f457c02ac62d8b1d3641a4582a to your computer and use it in GitHub Desktop.
React error boundary component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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