react-native-error-boundary

Travis Build Status
Codecov
Npm Version
Npm Downloads

A simple and reusable React-Native error boundary component 🐛

Install

$ yarn add react-native-error-boundary

Usage

This component catches JavaScript errors anywhere in their child component tree. Native errors are not handled.

Using this component is really simple. First you have to import the ErrorBoundary component. Then, you have to wrap it around any component that could throw an error.

Basic

import ErrorBoundary from 'react-native-error-boundary'

const App = () => (
  <ErrorBoundary>
    <ChildrenThatCouldThrowEror />
  </ErrorBoundary>
)

Logging errors

You can log the error by providing an onError function to the component.

import ErrorBoundary from 'react-native-error-boundary'

const errorHandler = (error: Error, stackTrace: string) => {
  /* Log the error to an error reporting service */
}

const App = () => (
  <ErrorBoundary onError={errorHandler}>
    <ChildrenThatCouldThrowEror />
  </ErrorBoundary>
)

Custom fallback component

You can customize the appearance of the fallback component by providing the FallbackComponent prop.

import ErrorBoundary from 'react-native-error-boundary'

const CustomFallback = (props: { error: Error, resetError: Function }) => (
  <View>
    <Text>Something happened!</Text>
    <Text>{props.error.toString()}</Text>
    <Button onPress={props.resetError} title={'Try again'} />
  </View>
)

const App = () => (
  <ErrorBoundary FallbackComponent={CustomFallback}>
    <ChildrenThatCouldThrowEror></ChildrenThatCouldThrowEror>
  </ErrorBoundary>
)

API

ErrorBoundary

These are the props that the ErrorBoundary component accepts:

PropertyTypeRequiredDefaultDescription
childrenReact.ChildrentrueComponents that may throw an error
FallbackComponentReact.ComponentfalseFallbackComponentUI rendered when there’s an error
onErrorFunctionfalseFunction for logging the error

FallbackComponent

These are the props that the FallbackComponent receives:

PropertyTypeDefaultDescription
errorErrorThe thrown error
resetErrorFunctionA function to reset the error state

Demo

react-native-error-boundary