shinke1987.net
雑多な備忘録等のはず。
他のカテゴリ・タブ
目次
PR

React:ErrorBoundaryコンポーネントの動作確認

2024-05-17 2024-05-17
カテゴリ: React

環境

React:v18.3.1

資料

Tips

以下のパターンがある。

インストール

下記コマンドを実行して、ErrorBoundaryコンポーネントをインストールする。

% npm install react-error-boundary

コード

ErrorBoundaryParent.tsxの内容

import { ErrorBoundary } from 'react-error-boundary';
import { MouseEventHandler, ReactNode } from 'react';
import ErrorBoundaryChild from './ErrorBoundaryChild.tsx';
import ErrorBoundaryChildFunc from './ErrorBoundaryChildFunc.tsx';

type handleFallbackProps = {
  error: Error,
  resetErrorBoundary: MouseEventHandler,
}

function ErrorBoundaryParent(): ReactNode {
  const handleFallback = ({ error, resetErrorBoundary }: handleFallbackProps) => (
    <>
      <div>
        以下のエラーが発生しました。
      </div>
      <p>{error.message}</p>
      <button
        type="button"
        onClick={resetErrorBoundary}
      >
        Retry
      </button>
    </>
  );

  const handleReset = () => {
    console.log('Retryボタンがクリックされました');
  };

  return (
    <>
      <div>
        ErrorBoundaryParent.tsx
      </div>

      <hr />
      <br />
      <ErrorBoundary
        fallback={<div>エラーが発生しました</div>}
        onError={(error) => console.log('ErrorBoundaryParent error = ', error)}
      >
        <ErrorBoundaryChild />
      </ErrorBoundary>

      <hr />
      <br />
      <ErrorBoundary
        onReset={handleReset}
        fallbackRender={handleFallback}
      >
        <ErrorBoundaryChild />
      </ErrorBoundary>

      <hr />
      <br />
      <ErrorBoundary
        fallback={<div>ErrorBoundaryChildFuncでエラーが発生しました</div>}
        onError={(error) => console.log('ErrorBoundaryChildFunc error = ', error)}
      >
        <ErrorBoundaryChildFunc />
      </ErrorBoundary>
    </>
  );
}

export default ErrorBoundaryParent;

ErrorBoundaryChild.tsxの内容

function ErrorBoundaryChild() {
  throw new Error('ErrorBoundaryChild Error');

  return (
    <div>
      ErrorBoundaryChild.tsx
    </div>
  );
}

export default ErrorBoundaryChild;

ErrorBoundaryChildFunc.tsxの内容

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

function ErrorBoundaryChildFunc() {
  const { showBoundary } = useErrorBoundary();
  const handleBtnClick = () => {
    try {
      throw new Error('ErrorBoundaryChildFunc');
    } catch (e) {
      showBoundary(e);
    }
  };

  return (
    <>
      <div>
        ErrorBoundaryChildFunc.tsx
      </div>
      <button
        type="button"
        onClick={handleBtnClick}
      >
        エラー発生
      </button>
    </>
  );
}

export default ErrorBoundaryChildFunc;

結果

初期表示は下記画像のようになる。

同一カテゴリの記事