How to Use PropTypes to Define Props in React
<p>React allows you to define the types of props given to your components to make sure that invalid data is not sent as the prop to the element. </p>
<p>To do this you can define <code>propTypes</code>.</p>
<p>You can define <code>propTypes </code>the same way that you define <a href="https://kruxor.com/view/code/PQwFO/how-to-use-default-props-in-react/searchtext:::defaultProps"><code>defaultProps</code></a>.</p>
<p>Here is a <a href="https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes" target="blank" rel="noopener">list of other proptypes</a> available to check and <a href="https://www.npmjs.com/package/prop-types" target="_blank" rel="noopener">as of 15.5 these ones</a>. </p>
<h4>Javascript</h4>
<pre><code class="javascript hljs">MyComponent.propTypes = {<br /> // You can declare that a prop is a specific JS primitive. By default, these<br /> // are all optional.<br /> optionalArray: PropTypes.array,<br /> optionalBool: PropTypes.bool,<br /> optionalFunc: PropTypes.func,<br /> optionalNumber: PropTypes.number,<br /> optionalObject: PropTypes.object,<br /> optionalString: PropTypes.string,<br /> optionalSymbol: PropTypes.symbol,<br /> <br /> // Anything that can be rendered: numbers, strings, elements or an array<br /> // (or fragment) containing these types.<br /> optionalNode: PropTypes.node,<br /> <br /> // A React element (ie. <MyComponent />).<br /> optionalElement: PropTypes.element,<br /> <br /> // A React element type (ie. MyComponent).<br /> optionalElementType: PropTypes.elementType,<br /> <br /> // You can also declare that a prop is an instance of a class. This uses<br /> // JS's instanceof operator.<br /> optionalMessage: PropTypes.instanceOf(Message),<br /> <br /> // You can ensure that your prop is limited to specific values by treating<br /> // it as an enum.<br /> optionalEnum: PropTypes.oneOf(['News', 'Photos']),<br /> <br /> // An object that could be one of many types<br /> optionalUnion: PropTypes.oneOfType([<br /> PropTypes.string,<br /> PropTypes.number,<br /> PropTypes.instanceOf(Message)<br /> ]),<br /> <br /> // An array of a certain type<br /> optionalArrayOf: PropTypes.arrayOf(PropTypes.number),<br /> <br /> // An object with property values of a certain type<br /> optionalObjectOf: PropTypes.objectOf(PropTypes.number),<br /> <br /> // You can chain any of the above with isRequired to make sure a warning<br /> // is shown if the prop isn't provided.<br /> <br /> // An object taking on a particular shape<br /> optionalObjectWithShape: PropTypes.shape({<br /> optionalProperty: PropTypes.string,<br /> requiredProperty: PropTypes.number.isRequired<br /> }),<br /> <br /> // An object with warnings on extra properties<br /> optionalObjectWithStrictShape: PropTypes.exact({<br /> optionalProperty: PropTypes.string,<br /> requiredProperty: PropTypes.number.isRequired<br /> }),<br /> <br /> requiredFunc: PropTypes.func.isRequired,<br /> <br /> // A value of any data type<br /> requiredAny: PropTypes.any.isRequired,<br /> <br /> // You can also specify a custom validator. It should return an Error<br /> // object if the validation fails. Don't console.warn or throw, as this<br /> // won't work inside oneOfType.<br /> customProp: function(props, propName, componentName) {<br /> if (!/matchme/.test(props[propName])) {<br /> return new Error(<br /> 'Invalid prop ' + propName + ' supplied to' +<br /> ' ' + componentName + '. Validation failed.'<br /> );<br /> }<br /> },<br /> <br /> // You can also supply a custom validator to arrayOf and objectOf.<br /> // It should return an Error object if the validation fails. The validator<br /> // will be called for each key in the array or object. The first two<br /> // arguments of the validator are the array or object itself, and the<br /> // current item's key.<br /> customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {<br /> if (!/matchme/.test(propValue[key])) {<br /> return new Error(<br /> 'Invalid prop ' + propFullName + ' supplied to' +<br /> ' ' + componentName + '. Validation failed.'<br /> );<br /> }<br /> })<br />};</code></pre>
<p> </p>
HTML
<div id="challenge-node"></div>Scripts
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0-alpha-5fa4d79b0-20211008/umd/react.production.min.js" integrity="sha512-5PVmWGoNJocWPdQJmJd1aRbz3cFcFgXctWKLWcitqtgX64jF+ttfg9g2oLltmeQ1HUo3gT6QchaMK3h+S+JG4Q==" crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0-alpha-5fa4d79b0-20211008/umd/react-dom.production.min.js" integrity="sha512-pUsjUv+9XgkTn+UbLyNIT4YNZPF2p0E45FBKmDL7Ti8iovYwp2CUkQs6Q7J9y5scLxWaOM+T5jJc0ls+WHUcmQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
const Items = (props) => {
return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
};
// Change code below this line
Items.propTypes = { quantity: PropTypes.number.isRequired }
// Change code above this line
Items.defaultProps = {
quantity: 0
};
class ShoppingCart extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Items />
}
};
ReactDOM.render(<ShoppingCart />, document.getElementById('challenge-node'));</script>