ErrorBoundary in React

RMAG news

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;

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)

Leave a Reply

Your email address will not be published. Required fields are marked *