Skip to content

Instantly share code, notes, and snippets.

@theham3d
Created November 1, 2018 22:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theham3d/f0ee89e5f99c4ff8433d875d04936d52 to your computer and use it in GitHub Desktop.
Save theham3d/f0ee89e5f99c4ff8433d875d04936d52 to your computer and use it in GitHub Desktop.
getDerivedStateFromError Example
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