Created
November 1, 2018 22:37
-
-
Save theham3d/f0ee89e5f99c4ff8433d875d04936d52 to your computer and use it in GitHub Desktop.
getDerivedStateFromError 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
import React , { Component } from 'react'; | |
class CatchError extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { hasError: false }; | |
} | |
static getDerivedStateFromError(error) { | |
// if something happens this will update state so the next render will show our fallback UI. | |
return { hasError: true }; | |
} | |
render() { | |
const { hasError } = this.state; | |
const { children } = this.props; | |
if (hasError) { | |
// render anything you want for fallback ui | |
return <h1>Something went wrong.</h1>; | |
} | |
return children; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment