The empty array [] passes the following PropTypes definition, even though we state that the string elements are mandatory.
{
a: React.PropTypes.arrayOf(
React.PropTypes.string.isRequired
).isRequired
}
On the contrary, the empty object {} does not pass the following propTypes definition:
{
a: React.PropTypes.shape({
x: PropTypes.string.isRequired
}).isRequired
}
Array validation seems to be not working correctly. Any ideas?
You could utilize the custom validator. I don't believe you can enforce the string.isRequired
inside the arrayOf when there are no items.. judging from how the custom validator of an arrayOf works, it seems to invoke the callback on each key. So, if the value has no keys, then no validators would be called.
(Note, this isn't tested)
a: function(props, propName, componentName) {
var errorCount = 0
var prop = props[propName]
// ensure it is an array
if (typeof prop !== 'array') {
errorCount++
}
// ensure array has items
else if (prop.length == 0) {
errorCount++
}
// ensure all items are strings
else {
for (var i = 0; i < prop.length; i++) {
if (typeof prop[i] !== 'string') errorCount++
}
}
// throw error
if (errorCount > 0) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
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