Created
January 12, 2019 14:30
-
-
Save faisalhmohd/d23fb2d65a06c95e6e8f96a2ef75980b to your computer and use it in GitHub Desktop.
React v16 Error Boundary Example
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="description" content="React v16 Error Boundary Implementation"> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> | |
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div id="app"></div> | |
</body> | |
</html> |
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
class ErrorBoundary extends React.Component { | |
constructor(props) { | |
super(props); | |
} | |
componentDidCatch(error, errorInfo) { | |
console.log(error, errorInfo); | |
} | |
render() { | |
return this.props.children; | |
} | |
} | |
function triggerError() { | |
throw new Error('An Error that should be caught!'); | |
} | |
function ComponentOne() { | |
return ( | |
<div> | |
ComponentOne | |
<span onClick={triggerError}>Trigger Error</span> | |
<ComponentOneChild /> | |
</div> | |
); | |
} | |
function triggerFunction() { | |
console.log('I am running!'); | |
} | |
function ComponentOneChild() { | |
return ( | |
<div> | |
ComponentOneChild | |
<span onClick={triggerFunction}>Execute Another Function</span> | |
</div> | |
); | |
} | |
function ComponentTwo() { | |
return( | |
<div> | |
ComponentTwo | |
<ComponentTwoChild /> | |
</div> | |
); | |
} | |
function ComponentTwoChild() { | |
return ( | |
<div> | |
ComponentTwoChild | |
</div> | |
); | |
} | |
function MainApp() { | |
console.log('MainApp:Render'); | |
return ( | |
<div> | |
<ErrorBoundary> | |
<ComponentOne /> | |
</ErrorBoundary> | |
<br /> | |
<ComponentTwo /> | |
</div> | |
); | |
} | |
ReactDOM.render(<MainApp />, document.querySelector("#app")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment