Type checking properties with PropTypes

React allows you to implement runtime type checking of components' properties. It's useful to catch bugs and make sure that your components are receiving props correctly. This can be easily done by just setting a static propType property on your components. For instance:

class MyComponent extends React.Component { 
   static propTypes = { 
      children: propTypes.string.isRequired, 
   } 
   render() { 
      return<span>{this.props.children}</span> 
   } 
} 

The previous code will require MyComponent's children property to be a string. Otherwise, if a different property type is given, React will display a warning in the console.

propTypes' methods are functions that get triggered when the component's instance is created to check if the given props match the propTypes schema.

propTypes have an extensive list of methods that can be used for the validation of properties. You can find the complete list in the React official documentation: https://reactjs.org/docs/typechecking-with-proptypes.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.146.77