Validating multiple values
React PropTypes provides a feature named multiple validation of props, this feature helps in validating either one or more prop values or it’s types simultaneously.
Example: Implementation to showcase the validation of multiple values using PropTypes.
// myComponent.js
import PropTypes from 'prop-types'
function MyComponent({ name, value }) {
return (
<div>
<h1>{name}</h1>
<h1>{value}</h1>
</div>
)
}
MyComponent.propTypes = {
name: PropTypes.oneOf([40, 'Sample']),
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
};
export default MyComponent;
Output:
Explanation: In the example mentioned above, we are validating two properties, namely “name” and “value”. We are checking if the “name” property has any of the two specified values, namely 40 or ‘Samples’. As the “name” property does not have either of these values, a warning is generated in the console. However, since the “value” property is of the “number” type, it does not generate any errors.
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.