Search code examples
javascriptreactjsreact-proptypes

Behavior of PropTypes.func.isRequired for error handling


I am new to React and trying to understand an existing project codebase that I need to work on. In two component classes, I see they define the onError property of type PropTypes.func as below.

MyComp.jsx

MyComp.propTypes = {
  //other properties
  onError: PropTypes.func.isRequired,
};

This property is set at multiple places in the class in the catch block as follows.

SomerService.someFunc()
.then(() => { // some code  
})
.catch((e) => onError(e));

OR

try {
  //some code
} catch (e) {
  onError(e);
}

Based on my little understanding, I was expecting that since the property type is PropTypes.func there should be a function named onError which basically handles the error or show an error message or something like that. But there is no such method anywhere in the code. So, what exactly does it do? And how are those exceptions/errors handled?


Solution

  • PropTypes are used to validate(to check the type of prop) the props passed to the component.

    https://www.npmjs.com/package/prop-types

    in your case, the MyComp component accepts the onError prop, whose type is .func (a function). and .isRequired means that you should send the onError prop to MyComp component whenever you use MyComp.

    <MyComp onError={(e)=>{/*function to handle error*/}} />