4.1.2 • Published 1 month ago

react-error-boundary v4.1.2

Weekly downloads
491,652
License
MIT
Repository
github
Last release
1 month ago

react-error-boundary

Reusable React error boundary component. Supports all React renderers (including React DOM and React Native).

If you like this project, 🎉 become a sponsor or ☕ buy me a coffee

Getting started

# npm
npm install react-error-boundary

# pnpm
pnpm add react-error-boundary

# yarn
yarn add react-error-boundary

API

ErrorBoundary component

Wrap an ErrorBoundary component around other React components to "catch" errors and render a fallback UI. The component supports several ways to render a fallback (as shown below).

Note ErrorBoundary is a client component. You can only pass props to it that are serializeable or use it in files that have a "use client"; directive.

ErrorBoundary with fallback prop

The simplest way to render a default "something went wrong" type of error message.

"use client";

import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary fallback={<div>Something went wrong</div>}>
  <ExampleApplication />
</ErrorBoundary>

ErrorBoundary with fallbackRender prop

"Render prop" function responsible for returning a fallback UI based on a thrown value.

"use client";

import { ErrorBoundary } from "react-error-boundary";

function fallbackRender({ error, resetErrorBoundary }) {
  // Call resetErrorBoundary() to reset the error boundary and retry the render.

  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
    </div>
  );
}

<ErrorBoundary
  fallbackRender={fallbackRender}
  onReset={(details) => {
    // Reset the state of your app so the error doesn't happen again
  }}
>
  <ExampleApplication />
</ErrorBoundary>;

ErrorBoundary with FallbackComponent prop

React component responsible for returning a fallback UI based on a thrown value.

"use client";

import { ErrorBoundary } from "react-error-boundary";

function Fallback({ error, resetErrorBoundary }) {
  // Call resetErrorBoundary() to reset the error boundary and retry the render.

  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
    </div>
  );
}

<ErrorBoundary
  FallbackComponent={Fallback}
  onReset={(details) => {
    // Reset the state of your app so the error doesn't happen again
  }}
>
  <ExampleApplication />
</ErrorBoundary>;

Logging errors with onError

"use client";

import { ErrorBoundary } from "react-error-boundary";

const logError = (error: Error, info: { componentStack: string }) => {
  // Do something with the error, e.g. log to an external API
};

const ui = (
  <ErrorBoundary FallbackComponent={ErrorFallback} onError={logError}>
    <ExampleApplication />
  </ErrorBoundary>
);

useErrorBoundary hook

Convenience hook for imperatively showing or dismissing error boundaries.

Show the nearest error boundary from an event handler

React only handles errors thrown during render or during component lifecycle methods (e.g. effects and did-mount/did-update). Errors thrown in event handlers, or after async code has run, will not be caught.

This hook can be used to pass those errors to the nearest error boundary:

"use client";

import { useErrorBoundary } from "react-error-boundary";

function Example() {
  const { showBoundary } = useErrorBoundary();

  useEffect(() => {
    fetchGreeting(name).then(
      response => {
        // Set data in state and re-render
      },
      error => {
        // Show error boundary
        showBoundary(error);
      }
    );
  });

  // Render ...
}

Dismiss the nearest error boundary

A fallback component can use this hook to request the nearest error boundary retry the render that originally failed.

"use client";

import { useErrorBoundary } from "react-error-boundary";

function ErrorFallback({ error }) {
  const { resetBoundary } = useErrorBoundary();

  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{ color: "red" }}>{error.message}</pre>
      <button onClick={resetBoundary}>Try again</button>
    </div>
  );
}

withErrorBoundary HOC

This package can also be used as a higher-order component that accepts all of the same props as above:

"use client";

import {withErrorBoundary} from 'react-error-boundary'

const ComponentWithErrorBoundary = withErrorBoundary(ExampleComponent, {
  fallback: <div>Something went wrong</div>,
  onError(error, info) {
    // Do something with the error
    // E.g. log to an error logging client here
  },
})

// Can be rendered as <ComponentWithErrorBoundary {...props} />

FAQ

ErrorBoundary cannot be used as a JSX component

This error can be caused by a version mismatch between react and @types/react. To fix this, ensure that both match exactly, e.g.:

If using NPM:

{
  ...
  "overrides": {
    "@types/react": "17.0.60"
  },
  ...
}

If using Yarn:

{
  ...
  "resolutions": {
    "@types/react": "17.0.60"
  },
  ...
}

This blog post shows more examples of how this package can be used, although it was written for the version 3 API.

@yuants/ui-web@shesha/reactjs@ohri/openmrs-ohri-form-engine-lib@triplex/editor@triplex/scenebys-containerdbn-ui-test-1react-qckryptokrona-desktop-wallet@ricado/error-handlercoreqlmicurai-pluginmango-web-app-brcaptain-dashboardsredux-chess@chesslab/redux-chessstrapi-new-admin@djaouli/react-spectrumdakozalvyue-mobile1@biyectiva/create-biyectiva-applog8000v3@agros/build-scripts@teamfabric/storefront-uiberserk-adminreact-ts-form-gen-elements@infinitebrahmanuniverse/nolb-react-erhce-saasassisted-ui-lib@zpnester/bs-router@knapsack/app-uireact-mui-form-generatorsupport-worksuiteka-loginka-productpageka-receiptlazarus-ui-frameworkfo-test2caroumesh-backup@everything-registry/sub-chunk-2553@polkadot-cloud/recipes-testthree-fiber-xr-error-boundarywebpmp-theme@paiondata/lexical-playground@paiondata/lexical-reactdatav-amis@yme/lay-antdshesha-reactjs-starterboxfusion-test-modulebys-container-ui2@spencerlepine/connect-chat-frontend-componentsveridicallane-testmf-package-lerna-themesmf-packages@thiagoelg/kaoto-uiaminhp93-componentstcg-boilerplates-mfetcg-mfe-boilerplatestcg-mfes-boilerplatetavernswiggleit-ui-kit-2synapse-react-clienttaas-toolbartest-library-sopeewaleed-avocadowaleed-avocado-2wdc-chartswork-permit-spa-v3worroierwritlyx-star-designws-strapi-forkxlameiroxm-entadmin-mains31-editorrn-strapi-adminsharedbysaurabhshepherd-editorsanakalpchartssanity-plugin-fieldset-tabssanity-super-panesaurabhsharedcomprescript-react-error-boundaryreact-vite-starterreidoecommerceremasteredreviews-widgetreact.costco.webrmscomponentssuperset-plugin-chart-hello-world2telmed-mat-lib-devstarlord-ui-librarysun-ui-v0.1.5storybox-reactstory-bootstrapstorybook-source-linksteadybiz-travel-managementstoryuistrapi-admin
4.1.0

1 month ago

4.1.2

1 month ago

4.1.1

1 month ago

4.0.13

9 months ago

4.0.12

11 months ago

4.0.9

1 year ago

4.0.8

1 year ago

4.0.5

1 year ago

4.0.10

1 year ago

4.0.7

1 year ago

4.0.6

1 year ago

4.0.11

1 year ago

4.0.4

2 years ago

4.0.1

2 years ago

4.0.0

2 years ago

4.0.3

2 years ago

4.0.2

2 years ago

3.1.4

3 years ago

3.1.3

4 years ago

3.1.2

4 years ago

3.1.1

4 years ago

3.1.0

4 years ago

3.0.2

4 years ago

3.0.1

4 years ago

3.0.0

4 years ago

2.3.2

4 years ago

2.3.1

4 years ago

2.3.0

4 years ago

2.2.3

4 years ago

2.2.2

4 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.0

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.2.5

6 years ago

1.2.4

6 years ago

1.2.3

7 years ago

1.2.2

7 years ago

1.2.1

7 years ago

1.2.0

7 years ago

1.1.0

7 years ago

1.0.0

7 years ago

0.0.6

7 years ago

0.0.5

7 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago