Conditional type checking
PropTypes provides a feature to perform conditional type checking, it can be done by using a PropType “PropTypes.isRequired”.
Example : Suppose we have a requirement that a component should receive at least one prop and that prop must be of number type. In this case we would use “PropType.isRequired”.
import PropTypes from 'prop-types'
function MyComponent({value}) {
return (
<div>
<h1>{value}</h1>
</div>
)
}
MyComponent.defaultProps ={
value : 12
}
MyComponent.propTypes = {
value : PropTypes.number.isRequired
};
export default MyComponent;
Output:
Note: It generates a correct output as the requirements are met.
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.