Is it possible to use PropTypes.oneOf
to enforce the presence of either a specific type or a string literal?
Example:
display: PropTypes.oneOf([PropTypes.bool, 'autohide']),
Or is it simply treating PropTypes.bool as whatever literal value it returns? Couldn't find any reference to this in the official documentation, so I'm assuming it doesn't work as I expect it to work. It doesn't raise an error, though.
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.
5 PropTypes are deprecated in the React package and have been given a package of their own. Change is an inevitable part of life. The upshot is twofold. 1) If you use another type-checking mechanism, you don't have to worry about shipping unnecessary bulk to your end users.
Props are required in TypeScript In the prop-types package, all props are optional by default. To make a prop required, you will have to use . isRequired explicitly. With TypeScript, that is not the case.
What are PropTypes? 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.
You can nest oneOf()
into oneOfType()
like that
PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(['autohide'])
])
Yep, it's possible, but not directly. Actually you can have different PropTypes
this way:
display: PropTypes.oneOf([
true,
false,
'autohide'
]),
You know that the PropTypes.bool
is going to be either true
or false
. For an advanced use of validation, see the CustomValidation here: customArrayProp
.
Reference: Typechecking With PropTypes – React
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