Posted in react
998
4:40 am, October 19, 2021
 

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.&nbsp;</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>.&nbsp;</p>
<h4>Javascript</h4>
<pre><code class="javascript hljs">MyComponent.propTypes = {<br />&nbsp; // You can declare that a prop is a specific JS primitive. By default, these<br />&nbsp; // are all optional.<br />&nbsp; optionalArray: PropTypes.array,<br />&nbsp; optionalBool: PropTypes.bool,<br />&nbsp; optionalFunc: PropTypes.func,<br />&nbsp; optionalNumber: PropTypes.number,<br />&nbsp; optionalObject: PropTypes.object,<br />&nbsp; optionalString: PropTypes.string,<br />&nbsp; optionalSymbol: PropTypes.symbol,<br />&nbsp;<br />&nbsp; // Anything that can be rendered: numbers, strings, elements or an array<br />&nbsp; // (or fragment) containing these types.<br />&nbsp; optionalNode: PropTypes.node,<br />&nbsp;<br />&nbsp; // A React element (ie. &lt;MyComponent /&gt;).<br />&nbsp; optionalElement: PropTypes.element,<br />&nbsp;<br />&nbsp; // A React element type (ie. MyComponent).<br />&nbsp; optionalElementType: PropTypes.elementType,<br />&nbsp;<br />&nbsp; // You can also declare that a prop is an instance of a class. This uses<br />&nbsp; // JS's instanceof operator.<br />&nbsp; optionalMessage: PropTypes.instanceOf(Message),<br />&nbsp;<br />&nbsp; // You can ensure that your prop is limited to specific values by treating<br />&nbsp; // it as an enum.<br />&nbsp; optionalEnum: PropTypes.oneOf(['News', 'Photos']),<br />&nbsp;<br />&nbsp; // An object that could be one of many types<br />&nbsp; optionalUnion: PropTypes.oneOfType([<br />&nbsp; &nbsp; PropTypes.string,<br />&nbsp; &nbsp; PropTypes.number,<br />&nbsp; &nbsp; PropTypes.instanceOf(Message)<br />&nbsp; ]),<br />&nbsp;<br />&nbsp; // An array of a certain type<br />&nbsp; optionalArrayOf: PropTypes.arrayOf(PropTypes.number),<br />&nbsp;<br />&nbsp; // An object with property values of a certain type<br />&nbsp; optionalObjectOf: PropTypes.objectOf(PropTypes.number),<br />&nbsp;<br />&nbsp; // You can chain any of the above with isRequired to make sure a warning<br />&nbsp; // is shown if the prop isn't provided.<br />&nbsp;<br />&nbsp; // An object taking on a particular shape<br />&nbsp; optionalObjectWithShape: PropTypes.shape({<br />&nbsp; &nbsp; optionalProperty: PropTypes.string,<br />&nbsp; &nbsp; requiredProperty: PropTypes.number.isRequired<br />&nbsp; }),<br />&nbsp;<br />&nbsp; // An object with warnings on extra properties<br />&nbsp; optionalObjectWithStrictShape: PropTypes.exact({<br />&nbsp; &nbsp; optionalProperty: PropTypes.string,<br />&nbsp; &nbsp; requiredProperty: PropTypes.number.isRequired<br />&nbsp; }),<br />&nbsp;<br />&nbsp; requiredFunc: PropTypes.func.isRequired,<br />&nbsp;<br />&nbsp; // A value of any data type<br />&nbsp; requiredAny: PropTypes.any.isRequired,<br />&nbsp;<br />&nbsp; // You can also specify a custom validator. It should return an Error<br />&nbsp; // object if the validation fails. Don't console.warn or throw, as this<br />&nbsp; // won't work inside oneOfType.<br />&nbsp; customProp: function(props, propName, componentName) {<br />&nbsp; &nbsp; if (!/matchme/.test(props[propName])) {<br />&nbsp; &nbsp; &nbsp; return new Error(<br />&nbsp; &nbsp; &nbsp; &nbsp; 'Invalid prop ' + propName + ' supplied to' +<br />&nbsp; &nbsp; &nbsp; &nbsp; ' ' + componentName + '. Validation failed.'<br />&nbsp; &nbsp; &nbsp; );<br />&nbsp; &nbsp; }<br />&nbsp; },<br />&nbsp;<br />&nbsp; // You can also supply a custom validator to arrayOf and objectOf.<br />&nbsp; // It should return an Error object if the validation fails. The validator<br />&nbsp; // will be called for each key in the array or object. The first two<br />&nbsp; // arguments of the validator are the array or object itself, and the<br />&nbsp; // current item's key.<br />&nbsp; customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {<br />&nbsp; &nbsp; if (!/matchme/.test(propValue[key])) {<br />&nbsp; &nbsp; &nbsp; return new Error(<br />&nbsp; &nbsp; &nbsp; &nbsp; 'Invalid prop ' + propFullName + ' supplied to' +<br />&nbsp; &nbsp; &nbsp; &nbsp; ' ' + componentName + '. Validation failed.'<br />&nbsp; &nbsp; &nbsp; );<br />&nbsp; &nbsp; }<br />&nbsp; })<br />};</code></pre>
<p>&nbsp;</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>

View Statistics
This Week
327
This Month
1530
This Year
865

No Items Found.

Add Comment
Type in a Nick Name here
 
Related Search Terms
Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code here, mostly for my reference. Also if i find a good link, i usually add it here and then forget about it. more...

You could also follow me on twitter. I have a couple of youtube channels if you want to see some video related content. RuneScape 3, Minecraft and also a coding channel here Web Dev.

If you found something useful or like my work, you can buy me a coffee here. Mmm Coffee. ☕

❤️👩‍💻🎮

🪦 2000 - 16 Oct 2022 - Boots
Random Quote
I'm a big believer in energy and the secret and that sort of thing.
Unknown
Latest News
## 🚀 AI Giants Hit Bullseye: Anthropic & OpenAI Achieve Product-Market Fit Anthropic and OpenAI have reached a significant milestone, finding product-market fit with their AI technologies, which means their products effectively meet the needs of their customers, driving growth and adoption. This achievement showcases the practical value of their innovations, enabling businesses and individuals to leverage AI for enhanced productivity and efficiency. With this alignment of product and market needs, these companies are poised to transform industries and shape the future of technology.