We have an App.js file in React, and I would like to add an error boundary that wraps around the majority of routes. The App.js file broadly looks like this:
import { ErrorBoundary } from 'react-error-boundary';
function ErrorFallback({ error }) {
return (
<div role='alert'>
<p>Something went wrong:</p>
<pre style={{ color: 'red' }}>{error.message}</pre>
</div>
);
}
function App() {
return (
<React.Fragment>
<Navbar />
<Switch>
<Route exact path='/page1' component={comp1} />
<Route exact path='/page2' component={comp2} />
<Route exact path='/page3' component={comp3} />
<Route exact path='/page4' component={comp4} />
<Route exact path='/page5' component={comp5} />
<Route exact path='/page6' component={comp6} />
<Route component={NoMatch} />
</Switch>
<Footer />
<React.Fragment>
)
}
We are trying to use 1 ErrorBoundary to wrap all of the routes inside the <switch>. Note that the last route in the switch is a NoMatch component that renders if none of the other Routes render. If I try to render the ErrorBoundary inside of the <Switch>, as such:
<React.Fragment>
<Navbar />
<Switch>
<ErrorBoundary Fallback={ErrorFallback}>
<Route exact path='/page1' component={comp1} />
...
<Route component={NoMatch} />
</ErrorBoundary>
</Switch>
...
then for some reason, the NoMatch component always renders. And if I drag the NoMatch Route one row down (below the </ErrorBoundary>), then the NoMatch Route never renders (even when it should). On the other hand, if I wrap the </ErrorBoundary> around the entire <Switch>:
<ErrorBoundary Fallback={ErrorFallback}>
<Switch>
<Route exact path='/page1' component={comp1} />
...
<Route component={NoMatch} />
</Switch>
</ErrorBoundary>
..then the ErrorBoundary and the NoMatch both do seem to work. My question is - is this last code block the correct way to wrap multiple Routes in a React App.js file inside of a single ErrorBoundary?
Edit: I understand that there are tradeoffs to wrapping all of these routes inside of a single error boundary. For this instance, I am okay with this tradeoff, and the single error-boundary is by design (for now).