Exact props validation
PropTypes provides us a feature to validate, that whether we are having the same number of props, are of same order and same type.
Example: Implementation to showcase the exact props validation using PropTypes.
import PropTypes from 'prop-types'
function MyComponent({data}) {
return (
<div >
<h1>{data.name}</h1>
<h1>{data.value}</h1>
</div>
)
}
MyComponent.defaultProps ={
data :({
name : "sanjay",
value : 12,
value2 : 18,
})
}
MyComponent.propTypes = {
data : PropTypes.exact({
name :PropTypes.string,
value : PropTypes.number
})
};
export default MyComponent;
Output:
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.