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
You can checkout from the below link about react-error-boundary:-
https://www.npmjs.com/package/react-error-boundary
Now you are thinking how do we implement it So to implement it in your code you have to write the below code :-
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: