I've focused on validating the type of property values so far, but that's not always what you'll want to check for. Sometimes, specific values matter. Let's see how we can validate specific property values:
import React from "react";
import PropTypes from "prop-types";
const levels = new Array(10).fill(null).map((v, i) => i + 1);
const userShape = {
name: PropTypes.string,
age: PropTypes.number
};
export default function MyComponent({ level, user }) {
return (
<section>
<p>{level}</p>
<p>{user.name}</p>
<p>{user.age}</p>
</section>
);
}
MyComponent.propTypes = {
level: PropTypes.oneOf(levels),
user: PropTypes.shape(userShape)
};
The level property is expected to be a number from the levels array. This is easy to validate using the oneOf() function. The user property is expecting a specific shape. A shape is the expected properties and types of an...