Answer a question

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.

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

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐