Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Error Boundary in Components routed using react-router

I have a page which uses different components which is loaded using react router. Is it possible to integrate error boundary in each component as shown in the below code when I use the react router to route to different pages?

My target is to show errors particularly for individual components so that other components should work in case there is an error in one component.

Please see my code below:

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

registerServiceWorker();

App.js

import React, { Component } from 'react';
import {BrowserRouter as Router, Route, Link } from 'react-router-dom';
//import ErrorBoundary from "./errorboundary";
import MyComponent1 from './component1';
import MyComponent2 from './component2';

class App extends Component {
render() {
return (
<Router>
<div style={{ backgroundColor: 'green' }}>
<div style={{ backgroundColor: '#f0f0ae', height: '30px' }}>
<Link to='/'>Link 1</Link> &#160;&#160;
<Link to='/comp1'>Link 2</Link> &#160;&#160;
<Link to='/comp2'>Link 3</Link> &#160;&#160;
</div>

<div style={{ backgroundColor: '#ffc993', height: '150px' }}>
<Route path='/' exact render={() => <MyComponent1 title="Component 1" />} />
<Route path='/comp1' render={() => <MyComponent1 title="Component 1 Again" />} />
<Route path='/comp2' render={() => <MyComponent2 title="Component 2" />} />
</div>
</div>
</Router>
);
}
}

export default App;

This is one of the component in which I want to use Error Boundary.

component1.js

import React, { Component } from 'react';
import ErrorBoundary from "./errorboundary";

class MyComponent1 extends Component {
state = {
boom: false,
};

throwError = () => this.setState({ boom: true });

render() {
const { title } = this.props;

if(this.state.boom) {
throw new Error(`${title} throw an error!`);
}

return (
<ErrorBoundary>
<input type='button' onClick={this.throwError} value={title} />
</ErrorBoundary>
)
}
}

export default MyComponent1;

This is another component in which I want to use the Error Boundary.

component2.js

import React, { Component } from 'react';
import ErrorBoundary from "./errorboundary";

class MyComponent2 extends Component {
state = {
boom: false,
};

throwError = () => this.setState({ boom: true });

render() {
const { title } = this.props;

if(this.state.boom) {
throw new Error(`${title} throw an error!`);
}

return (
<ErrorBoundary>
<input type='button' onClick={this.throwError} value={title} />
</ErrorBoundary>
)
}
}

export default MyComponent2;

This is my customized error message using error boundary when there is an error in each component.

errorboundary.js

import React, { Component } from 'react';

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

if(this.props.showError === false)
{
this.state.error = null;
this.state.errorInfo = null;
}
}

componentDidCatch = (error, info) => {
console.log("error did catch");
this.setState({error: error, errorInfo: info });        
}

render() {
if(this.state.errorInfo) {
return (
<div style={{ backgroundColor: '#ffcc99', color: 'white', width: '500px', height: '60px' }}>
An Error Occurred !
</div>
);
}
else {
return this.props.children;
}
}
}

export default ErrorBoundary;

Can anyone please help me? I am a newbie in React JS.

like image 334
DXB-DEV Avatar asked Mar 06 '18 12:03

DXB-DEV


2 Answers

You are not using the ErrorBoundary at the correct place. Wrapping an ErrorBoundary around input tag only make sure that if there is an error in the input, that is getting caught by the ErrorBoundary

return (
    <ErrorBoundary>   {/* errorBounday here only catches error in input */}
        <input type='button' onClick={this.throwError} value={title} />
    </ErrorBoundary>
)

You need to wrap your ErrorBoundary around components that throw the error like

<Route
          path="/comp1"
          render={() => (
            <ErrorBoundary>
              <MyComponent1 title="Component 1 Again" />
            </ErrorBoundary>
          )}
        />

In this way if the MyComponent1 throws an error it being caught by the error boundary which is the case for you. Your code would look like

class App extends React.Component {
  render() {
    return (
      <Router>
        <div style={{ backgroundColor: "green" }}>
          <div style={{ backgroundColor: "#f0f0ae", height: "30px" }}>
            <Link to="/">Link 1</Link> &#160;&#160;
            <Link to="/comp1">Link 2</Link> &#160;&#160;
            <Link to="/comp2">Link 3</Link> &#160;&#160;
          </div>

          <div style={{ backgroundColor: "#ffc993", height: "150px" }}>
            <Route
              path="/"
              exact
              render={() => (
                <ErrorBoundary>
                  <MyComponent1 title="Component 1" />
                </ErrorBoundary>
              )}
            />
            <Route
              path="/comp1"
              render={() => (
                <ErrorBoundary>
                  <MyComponent1 title="Component 1 Again" />
                </ErrorBoundary>
              )}
            />
            <Route
              path="/comp2"
              render={() => (
                <ErrorBoundary>
                  <MyComponent2 title="Component 2" />
                </ErrorBoundary>
              )}
            />
          </div>
        </div>
      </Router>
    );
  }
}

DEMO

Do read this question for understanding how to test ErrorBoundaries in codesandbox

like image 198
Shubham Khatri Avatar answered Sep 29 '22 22:09

Shubham Khatri


Wrap your main router outlets with ErrorBoundary but provide a unique key to ErrorBoundary to force it to teardown and build a new instance when the location changes:

export const AppRouter = () => {
  const location = useLocation();

  return (
    <main>
      <ErrorBoundary key={location.pathname}>
        <Switch>
          <Route path="/" component={Dashboard} />
          <Route path="/orders" component={Orders} />
        </Switch>
      </ErrorBoundary>
    </main>
  );
};

Be warned, this simple but lazy solution will cause unneccessary renders of everything within ErrorBoundary whenever the location changes. You could get around this possibly by calculating a less-frequently-changing key based on the pathname instead of using the whole pathname itself.

like image 38
ilovett Avatar answered Sep 29 '22 23:09

ilovett