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:
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:
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:
Recommended by LinkedIn
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:
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:
#opentowork #hireme #opentoconnect