I was trying to use the react error boundary in my typescript react app but it doesn't seem to be working. Whenever there is an error that breaks the application, the fallback UI does not get rendered
ErrorBoundary.tsx
import React, {Component} from 'react'
class ErrorBoundary extends Component<{children:JSX.Element}, { hasError: boolean }> {
constructor(props: { children: JSX.Element; } | Readonly<{ children: JSX.Element; }>) {
super(props)
this.state = {
hasError: false
};
}
static getDerivedStateFromError(error: any) {
return { hasError: true };
}
render() {
if(this.state.hasError == true){
return <h1>Something went wrong</h1>
}else{
return this.props.children;
}
}
}
export default ErrorBoundary;
App.tsx
import { useContext, useState, useEffect, FC} from 'react';
import { AccessContexts } from './components/Contexts';
import Context from './components/Contexts';
import { Route, Routes, BrowserRouter} from 'react-router-dom';
import ErrorBoundary from './components/ErrorBoundary';
import Dashboard from './pages/Dashboard';
function App(){
return (
<AccessContexts>
<MyRoutes />
</AccessContexts>
);
}
export default App;
function MyRoutes() {
return (
<div className="App">
<ErrorBoundary>
<BrowserRouter>
<Routes>
<Route path='/dashboard' element={<Dashboard />}/>
</Routes>
</BrowserRouter>
</ErrorBoundary>
</div>
)
}
I am using the ErrorBoundary component in MyRoutes
Thanks for your help