How to catch the errors in react using error boundaries
In this post we will give you information about How to catch the errors in react using error boundaries. Hear we will give you detail about How to catch the errors in react using error boundariesAnd how to use it also give you demo for it if it is necessary.
we are going to learn about how to catch the errors in react using error boundaries.
What is an Error boundary?
In the past, we don’t have a way to catch the errors in React components and we are seeingsome cryptic errors in case our app breaks.
React 16 introduces a new way to catch errors by using the error boundaries.
Error boundaries are react components which helps us to catch the errors anywhere in our app and renders the fallback UI.
Error boundaries don’t break the whole App component tree instead of it only renders the fallback UIon an error occurred component.
Error boundaries are only defined in a class-based components.
Let’s see an example
We are using the componentDidCatch lifecycle method to update the error state and logging the errorInfo in the console.
class ErrorBoundary extends Component { state = { error: false, errorInfo: null }; componentDidCatch(error, errorInfo) { this.setState({ error: error, errorInfo: errorInfo }); } render() { if (this.state.error) { return ( <div style={{ whiteSpace: "pre" }}> <h2>Something went wrong</h2> {this.state.error && this.state.error.toString()} <br /> <p>Error occured {this.state.errorInfo.componentStack}</p> </div> ); } return this.props.children; }}
The ErrorBoundary component only renders the fallback UI if an error has occurred otherwise we are rendering the children.
Let’s use the ErrorBoundary component to catch the errors.
function Welcome(props) { return <h1>{props.name}</h1>;}function App(props) { return ( <div> <ErrorBoundary> <Welcome /> </ErrorBoundary> <br /> <h2>Date Component is working</h2> <Date /> </div> );}
In the above code, we wrapped the Welcome component with an ErrorBoundary component.
Output
The Welcome component is rendering the fallback UI because we failed to pass a name prop and our remaining part of the app is working fine.
Where to place ErrorBoundary components?
You can use it on the top level of your app components or you can wrap it on the individual components to stop the breaking the other parts of the app.
Hope this code and post will helped you for implement How to catch the errors in react using error boundaries. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs