React Error Boundaries Components with TypeScript

React Error Boundaries Components with TypeScript

In this quick tutorial, we are going to learn how to use Error Boundaries in React with TypeScript. By the end of this tutorial, you should be able to write your own Error Boundaries components.

In order to begin, we first need to download the starter code.

git clone https://github.com/rbarbosa51/tutorial-ts-error-boundaries.git
cd tutorial-ts-error-boundaries
npm install        

First, let’s review the starter code. Open up the folder in your favorite Code Editor. It is a basic react project. It is set up with TypeScript and Tailwind for styling. Take a minute to explore the code.

Go to the "BuggyComponent.tsx", It is a normal TypeScript React Component except for a prop called throwError. This will be used later to simulate an error.

...
interface myProps extends React.HtmlHTMLAttributes<HTMLDivElement> {
  throwError?: boolean;
}
export default function BuggyComponent({
  className,
  throwError,
  ...props
}: myProps) {
  if (throwError) {
    throw new Error("Ohh No there was an error!");
  }
...        

Now start the server and the open the browser with the correct localhost

npm run dev        

Your screen should look like this:

Article content

Go to the App.tsx file and in the BuggyComponent, add an attribute called throwError

<BuggyComponent throwError className="mx-auto mt-4 flex w-[75%] flex-col items-center justify-center text-center">        

If you are still running the web server. You should now see a blank screen. Take a look at the Developer Tools -> Console.log. You should see:

Article content

Now let's fix this. Go to the ErrorBoundary.tsx file. Error Boundaries in React use class components. First type the following:

import { Component } from "react";

class ErrorBoundary extends Component {
  
}        

Then we are going to write a State and Props interfaces:

interface Props {
   children?: React.ReactNode
}
interface State {
   hasError: boolean
}        

Now inside the component write the following:

export class ErrorBoundary extends Component<Props,State> {
   state: State = {
       hasError: false
   }
   render() {
       return this.props.children;
   }
}        

This sets the hasError as a component state; we will use this later to catch the error. The render function returns the children .

Go to the App.tsx file. Import the ErrorBoundary, then wrap the BuggyComponent with the ErrorBoundary.

   import { ErrorBoundary } from "./ErrorBoundary";        
......
<ErrorBoundary>
       <BuggyComponent throwError className="mx-auto mt-4 flex w-[75%] flex-col items-center justify-center text-center">
         Lorem ipsum dolor, ................
       </BuggyComponent>
 </ErrorBoundary>
.......        

Now go back to the ErrorBoundary.tsx. In the Props interface add an optional fallback ReactNode:

interface Props {
   children?: React.ReactNode
   fallback?: React.ReactNode
}        

Inside the ErrorBoundary class add a static function called getDerrivedFromError. This sets the hasError state to true in the event that a child component throws an Error. Write the following:

public static getDerivedStateFromError(_: Error): State {
       return { hasError: true };
}        

Inside the render function add an if statement that routes the rendering to a fallback component in the event of an Error.

render() {
       if (this.state.hasError) {
           return this.props.fallback;
       }
       return this.props.children;
}        

Your ErrorBoundary.tsx file should look like the following:

import { Component} from "react";
interface Props {
   children?: React.ReactNode
   fallback?: React.ReactNode
}
interface State {
   hasError: boolean
}
export class ErrorBoundary extends Component<Props,State> {
   state: State = {
       hasError: false
   }
   public static getDerivedStateFromError(_: Error): State {
       return { hasError: true };
     }
   render() {
       if (this.state.hasError) {
           return this.props.fallback;
       }
       return this.props.children;
   }
}        

In the src directory, create a new file called Fallback.tsx. Add the following code:

import error from './assets/error.jpeg'


interface myProps extends React.HTMLAttributes<HTMLDivElement> {}


export default function Fallback({className}: myProps) {
   return (
       <div className={className}>
           <img src={error} alt="Error" />
       </div>
   )
}        

Finally, go to the App.tsx file. Import the Fallback Component.

import Fallback from "./Fallback";        

Then add a fallback attribute to the ErrorBoundary component.

<ErrorBoundary fallback={<Fallback className="mx-auto mt-4 flex w-[75%] flex-col items-center justify-center text-center">Ohh No there was an error!</Fallback>}>        

Now your browser should show the fallback component:

Article content

Now you can toggle the error off and off and observed the render output:

<BuggyComponent throwError className="mx-auto mt-4 flex w-[75%] flex-col items-center justify-center text-center">
...
or
...
<BuggyComponent className="mx-auto mt-4 flex w-[75%] flex-col items-center justify-center text-center">        

Thank You! Hopefully this was useful to you. If you are having problems with the code, clone the finished branch

git clone https://github.com/rbarbosa51/tutorial-ts-error-boundaries.git -b Finished        

Are you looking for a good developer to add to your team? 

Feel free to look at my portfolio if you want to see a live example:

https://rafael-barbosa.com

#opentowork #hireme #opentoconnect


To view or add a comment, sign in

More articles by Rafael Barbosa

  • React 19 Compiler Tutorial

    In this quick tutorial, I will show you how you can upgrade a React-Vite program to use the new React 19 Compiler. For…

  • Learn how to use Zustand: the best Redux alternative.

    Zustand is a very simplistic alternative to the Redux state management library. It is fast intuitive and overall simple…

    1 Comment
  • Format.JS (React-Intl) Tutorial

    In this tutorial, we are going to learn how to localize your React app text. This can be very handy whenever we want to…

  • React QRCode Generator Tutorial

    In this tutorial, we will learn how to create a simple QR Code generator using the react-qr-code npm package. Before we…

  • React Sentiment Analysis Tutorial

    In this tutorial, We will use a Hugging Face (https://huggingface.co/) AI-pretrained model to create a React sentiment…

    1 Comment
  • React Three Fiber's Pointer Events Tutorial

    In this React Three Fiber tutorial, we will learn how to create simple animations based on Pointer events. First, we…

    8 Comments
  • React Three Fiber Tutorial

    In this simple tutorial, we are going to learn how to manipulate a 3D model with the use of the React-Three-Fiber…

    1 Comment

Others also viewed

Explore content categories