Validating Props Class name
To validate whether a prop belongs to a particular class or not using PropTypes, you can use the PropTypes.instanceOf(Class)
validator. This allows you to specify the class that the prop should be an instance of.
Example: This example validates the props class name.
//myComponent.js
import PropTypes from 'prop-types'
class Sample {
constructor(value) {
this.data= value.data;
}
}
function MyComponent({name}) {
return (
<div>
{name}
</div>
)
}
MyComponent.propTypes = {
name: PropTypes.instanceOf(Sample)
};
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.