In some examples, I have seen something like this:
Footer.propTypes = {
completedCount: PropTypes.number.isRequired,
activeCount: PropTypes.number.isRequired,
filter: PropTypes.string.isRequired,
onClearCompleted: PropTypes.func.isRequired,
onShow: PropTypes.func.isRequired
}
What are these PropTypes
really doing? Are they nice-to-have or must-have?
Props and PropTypes are important mechanisms for passing read-only attributes between React components. We can use React props, short for properties, to send data from one component to another. If a component receives the wrong type of props, it can cause bugs and unexpected errors in your app.
PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.
import React from 'react'; import PropTypes from 'prop-types'; function List(props) { const todos = props. todos. map((todo, index) => (<li key={index}>{todo}</li>)); return (<ul></ul>); } List. PropTypes = { todos: PropTypes.
PropTypes. node: any render-able value like numbers and string, that can actually be rendered on screen. PropTypes. any: any type of value, even those are non-render-able like boolean.
As pointed out by finalFreq I stand corrected! "the example provided will work perfectly fine in future versions of react. React deprecated calling the proptypes function directly but annotating a component will work just fine in current and future versions."
I suggest flowtypes if you are just learning types in JS, works at build time instead of run-time. This works in the editor! The editor extensions also use strong inference to alert you when a less obvious type is missing, null, or of a different type. The main benefit is that it speeds up development and reduces bugs without slowing run-time. You can easily strip the flow from your js before production.
FlowType: https://flowtype.org/docs/getting-started.html#_
I suggest TypeScript if you are wanting the more powerful and featureful set, to learn types in JS.
TypeScript: https://github.com/Microsoft/TypeScript
To answer your question proptypes were never a must have and were at one point considered experimental. I loved them, but flowtype is more pragmatic IMHO.The main use is to prevent the misuse of a component by warning early on in development and offer coded documentation for better understanding(posterity).
Edit: I also want to be clear that proptypes can be stripped for production also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With