Skip to content

Instantly share code, notes, and snippets.

@ridvanaltun
Last active August 25, 2021 19:26
Show Gist options
  • Select an option

  • Save ridvanaltun/e5dad6e8e687a3025b1a62fd5ad0776c to your computer and use it in GitHub Desktop.

Select an option

Save ridvanaltun/e5dad6e8e687a3025b1a62fd5ad0776c to your computer and use it in GitHub Desktop.
Error Boundaries in React Native
import React, {Component} from 'react';
import {Text, View} from 'react-native';
import CounterApp from '../Components/CounterApp';
import ErrorBoundries from '../Components/ErrorBoundries';
export default class AppContainer extends Component {
render() {
return (
<>
<Text style={{alignSelf: 'center', marginTop: 20}}>Counter App</Text>
<ErrorBoundries>
<CounterApp />
</ErrorBoundries>
</>
);
}
}
import React, {Component} from 'react';
import {Text, View} from 'react-native';
export default class ErrorBoundries extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: '',
errorInfo: '',
};
}
static getDerivedStateFromError(error) {
return {hasError: true};
}
componentDidCatch(error, errorInfo) {
console.log('Error: ' + error);
console.log('Error Info: ' + JSON.stringify(errorInfo));
this.setState({
error: error,
errorInfo: errorInfo,
});
}
render() {
if (this.state.hasError) {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginHorizontal: 12,
}}>
<Text>Oops!!! Something went wrong..</Text>
<Text>Error: {this.state.error.toString()}</Text>
<Text>Error Info: {JSON.stringify(this.state.errorInfo)}</Text>
</View>
);
}
return this.props.children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment