Created
November 9, 2017 19:28
-
-
Save ArunMichaelDsouza/e6aac33b2f5fa9184e1699493994c417 to your computer and use it in GitHub Desktop.
React 16 error boundaries demo
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 Child extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
error: false | |
}; | |
this.handleClick = this.handleClick.bind(this); | |
} | |
handleClick() { | |
this.setState({ error: true }); | |
} | |
render() { | |
if (this.state.error) { | |
throw new Error('I crashed!'); | |
} | |
return <button onClick = { this.handleClick }>Error</button>; | |
} | |
} | |
class Parent extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
errorInChild: false | |
}; | |
} | |
componentDidCatch() { | |
this.setState({ errorInChild: true }); | |
} | |
render() { | |
return this.state.errorInChild ? | |
<div>Error</div> : <Child />; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment