This is a short tutorial about creating a generic fallback error page in a react app.
create a new react application, add react-router-dom and start up the app:
npx create-react-app error-fallback-democd error-fallback-demoyarn add react-router-domyarn start
add some quick routing for demo purposes:
import './App.css';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import ErrorBoundary from "./ErrorBoundary";function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav> <Switch>
<ErrorBoundary>
<Route path="/about">
<About />
</Route>
</ErrorBoundary>
<Route path="/">
<Home />
</Route>
</Switch> </div>
</Router>
);
}function Home() {
return <h2>Home</h2>;
}function About() {
return <h2>About</h2>;
}export default App;
Now I want to throw an error to see what happens, so I put it in the about page like this:
function About() {
throw new Error('oh no!');
return <h2>About</h2>;
}
Now when I go to my ‘about’ page at http://localhost:3000/about I see this:
You will only see this in development mode, in production you will just see a blank page and if you click the ‘x’ in the top right you will see the blank page too.
I now make my error page to display, so I create a new file called ErrorPage:
import React from "react";const ErrorPage = (props) => { return (
<div>
<h2>An error has occurred. </h2>
</div>
);
};export default ErrorPage;
I need to create an error boundary to update the state so that the next render will show the fallback page. I got this from here https://reactjs.org/docs/error-boundaries.html.
I created a new file called ErrorBoundary:
import React from "react";
import ErrorPage from "./ErrorPage";class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
} static getDerivedStateFromError(error) {
return { hasError: true };
} render() {
if (this.state.hasError) {
return <ErrorPage />;
} return this.props.children;
}
}export default ErrorBoundary;
Now when we go to the /about page we should see our simple error page rendered:
Thanks for reading!