Custom PropTypes
Custom PropTypes enable developers to define their own validation logic for props beyond the built-in PropTypes validators, allowing for specific requirements or constraints enforcement on props passed to React components.
Example: Implementation to showcase the creation of custom props using PropTypes.
import PropTypes from 'prop-types'
function MyComponent({name}) {
return (
<div>
<h1>{name}</h1>
</div>
)
}
MyComponent.defaultProps ={
name : 12
}
MyComponent.propTypes = {
name(props, propName){
if(!/string/.test(props[propName])){
return new Error(`${propName} is not a string type`)
}
}
};
export default MyComponent;
Output:
Explanation: In the previous example, we set the “name” property with an integer value. However, in this new example, we created a custom hook that checks whether the received property is of the “string” type or not. As the received property is not of string type, it throws a warning on the console that says “name is not a string type”.
How to use PropTypes for Type-Checking in React Components ?
React is a JavaScript library for building user interfaces, and one of its key features is component-based architecture. When building React components, it’s essential to ensure that the data passed to them is of the correct type. PropTypes is a built-in type-checking library in React that helps developers validate the props passed to components during development.