Error Boundaries in React Functional Component

Hi Today we are going to learn about Error Boundary,How we can implement error boundary in react.

First install using npm command:-

npm install react-error-boundary

https://www.npmjs.com/package/react-error-boundary

import “./styles.css”;

import { ErrorBoundary } from “react-error-boundary”;

function City({ name }) {

return <div>Hi,Welcome to {name.toUpperCase()}</div>;

}

function Country({ name }) {

return <div>Hi Welcome to Country {name.toUpperCase()}</div>;

}

function ErrorHandler({ error }) {

return (

<div role=”alert”>

<pre>An error has occured</pre>

<p>{error.message}</p>

</div>

);

}

export default function App() {

return (

<div className=”App”>

<ErrorBoundary FallbackComponent={ErrorHandler}>

<City />

<Country />

</ErrorBoundary>

</div>

);

}

Now Error will show like this in below.

An error has occured

Cannot read properties of undefined (reading 'toUpperCase')

You can also refer for example:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akbar Sheikh

Software Developing is my hobby and want to learn more things everyday just like you