DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on

Rescript React Error boundary usage

Hi

I was trying to capture the react errors. I had to write the bindings for the ErrorBoundary and its usage is shown below.

The actual ErrorBoundary component is below

// ErrorBoundary.js
import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    //logErrorToMyService(error, errorInfo);
    console.log({ error, errorInfo });
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Enter fullscreen mode Exit fullscreen mode

Bindings to the ErrorBoundary for Rescript.

// ReactErrorBoundary.res
@react.component @module("./ErrorBoundary.js")
external make: (
  ~children: React.element,
  ~onError: ('e, 'i) => unit=?,
  ~renderFallback: ('e, 'i) => React.element=?,
) => React.element = "ErrorBoundary"

Enter fullscreen mode Exit fullscreen mode

Error component to show the react error

// Error.res
module Error = {
  @react.component
  let make = (~error) => {
    <div> {React.string(error)} </div>
  }
}

Enter fullscreen mode Exit fullscreen mode

How to use ReactErrorBoundary in rescript

// ReactErrorBoundary usage
<ReactErrorBoundary fallback={params => <Error 
  error=params.error />}>
  <ComponentThrowingException />
</ReactErrorBoundary>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)