How do I redirect within an ErrorBoundary?

6.6k Views Asked by At

I'm using ErrorBoundary in my React app and want to redirect to the main page when an error occurs - but my redirect is not working. Instead, the application stays on the same page.

In comparison, adding a button allows the user to switch pages on clicking it.

But I instead want to automatically take the user there when the error occurs.

Surely there must be an easy way to do this that I'm missing.

import React from 'react';
import { Redirect } from 'react-router-dom';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null, errorInfo: null };
  }

  componentDidCatch(error, errorInfo) {
    this.setState({
      error: error,
      errorInfo: errorInfo
    })
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.errorInfo) {
      return (
        <div>
          {/* <Button href="/index.html">Go Home</Button> */}
          <Redirect to="/index.html" />
        </div>
      );
    }

    return this.props.children; 
  }
}

export default ErrorBoundary;

I've also tried returning a Route with no luck:

render() {
  if (this.state.errorInfo) {
    return (
      <Route path="/Home" component={Home} />
    );
  }
1

There are 1 best solutions below

3
On BEST ANSWER

I am assuming you are also using react-router-dom inside your project.

Make sure that your ErrorBoundary component is inside the BrowserRouter wrapper in your index.js or App.js file. If so, you can simply connect your ErrorBoundary component to the react router by doing

export default withRouter(ErrorBoundary);

Make sure that it's imported correctly

import { withRouter } from 'react-router-dom';

If an error occurs you can then call:

this.props.history.push('/'); // will forward you to wherever you want

This will only change the url in the browser, depending on what else you have your ErrorBoundary doing you need to call

window.location.reload();

right after you pushed to the history. But this is only something you need to do when you configured your ErrorBoundary to overwrite your child props.