I have a component that receives a badge
prop (see example down below). The badge is optional, but once it is used I want it to have some required fields inside it. I've tried the following:
Component.propTypes = {
badge: PropTypes.shape({
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
}),
}
It works, but I get this warning on Chrome when trying to use it without the badge:
Warning: Failed prop type: The prop
badge.src
is marked as required inComponent
, but its value isnull
.
What is the proper way of doing this?
badge={{ src: 'usa.png', alt: 'United States' }}
badge
not supplied
propTypes = { //// key is the name of the prop and // value is the PropType } export default Count; PropTypes are also objects with a key and a value pair where the 'key' is the name of the prop while the value represents the type or class by which they are defined.
sargunv commented on May 3, 2017 •propTypes has been deprecated and will be removed in a future version of ReactNative.
To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.
Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.
This is the correct way to do this. I was very intrigued by how this wouldn't work, so I pasted it in a CodePen (https://codepen.io/Oblosys/pen/xLvxrd) and it works just as expected. (Open a console, and uncomment the failing one to see a prop-type error)
Something else must be going wrong in your code, and at some point you render a Component
with a badge property object that has src: null
. Maybe before data from an api request has arrived? With some console logging in Component
and its parent, you should be able to find the culprit.
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