- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ReactJS componentDidCatch method
In this article, we are going to see how to execute a function in the commit phase if some error occurs in the Component.
This method is called when a component or any children component encounters some error during the React Component Lifecycle. This method allows us to handle the error boundaries of the application.
Unlike the getDerivedStateFromError method, this method is called during the commit phase, so side-effects are also allowed in this method.
Syntax
componentDidCatch(err, data)
Parameters
err - Error thrown by the component.
data - Stores information about the component which has thrown the error.
Example
In this example, we will build a React application that displays the contained Comp component if no error occurs; otherwise it displays some text.
But here, in Comp component, error is defined to occur as the state is not defined which fires the componentDidCatch method in the parent component.
App.jsx
import React from 'react'; class App extends React.Component { constructor() { super(); this.state = { err: false, }; } componentDidCatch(error) { this.setState({ err: true, }); } render() { return ( <div> {this.state.err ? ( <div style={{border: '2px solid red',}}> Error </div> ) : ( <Comp/> )} </div> ); } } class Comp extends React.Component { render() { return <h1>{this.state.name}</h1>; } } export default App;
Output
This will produce the following result −
- Related Articles
- ReactJS – bind() method
- ReactJS – componentDidMount Method
- ReactJS – componentDidUpdate() Method
- ReactJS – componentWillMount() Method
- ReactJS – componentWillReceiveProps() Method
- ReactJS – componentWillUnmount() Method
- ReactJS – componentWillUpdate() Method
- ReactJS – createRef() method
- ReactJS – forceUpdate() Method
- ReactJS – getDerivedStateFromError() Method
- ReactJS – getDerivedStateFromProps() Method
- ReactJS – getSnapshotBeforeUpdate() Method
- ReactJS – shouldComponentUpdate() method
- ReactJS – Fragments
- Debugging ReactJS applications
