DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on

ErrorBoundary in React

ErrorBoundary

import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      err: false,
    };
  }
  static getDerivedStateFromError() {
    this.setState({ err: true });
  }

  render() {
    if (this.state.err) {
      return <h1>There is an error</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

Enter fullscreen mode Exit fullscreen mode

this.props.children -> this is the children of errorBoundary i.e. -> whatever is written inside the .

getDerivedStateFromError() -> lifecycle method for Error Boundary an is internally called in case of an error.

componentDidCatch() -> another lifecycle method which takes error, info as it's arguments and is used to log them.
componentDidCatch(error, info)

Top comments (0)