I'm trying to create a custom PropType that checks if an array has numerical values and has a length of 2 (and there's some constraint on the ordering of the numbers).
Obviously I can do Array.PropType.arrayOf(Array.PropType.number)
for the first two constraints.
I'd like to reuse this in my custom PropType (instead of rolling out my own numerical and array check).
How do I do that?
React.PropTypes.arrayOf( React.PropTypes.number )
just returns a function, so you can instead provide your own function to perform the validation.
Your function will be passed three parameters: props, propName, componentName
see the second to last example shown in React.PropTypes from the docs.
So a function that should satisfy your constraints would be:
function isTwoElementArrayOfNumbers( props, propName, componentName ){
var _array = props[ propName ];
if( _array && _array.constructor === Array && _array.length === 2 ){
if( !_array.every(
function isNumber( element ){
return typeof element === 'number';
})
){
return new Error('elements must be numbers!');
}
}
else{
return new Error('2 element array of numbers not provided!');
}
}
...in your react element
propTypes:{
numArray: isTwoElementArrayOfNumbers
},
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