React.PropTypes array with specific length
A custom function would be the correct approach here.
const propTypes = {
TWO_NUMBERS: arrayOfLength.bind(null, 2)
}
const arrayOfLength = (expectedLength, props, propName, componentName) => {
const arrayPropLength = props[propName].length
if (arrayPropLength !== expectedLength) {
return new Error(
`Invalid array length ${arrayPropLength} (expected ${expectedLength}) for prop ${propName} supplied to ${componentName}. Validation failed.`
)
}
}
In this case you would need to write your own special PropTypes function which react provides you to do.
const TWO_NUMBERS = function(props, propName, componentName) {
if (!Array.isArray(props.TWO_NUMBERS) || props.TWO_NUMBERS.length != 2 || !props.TWO_NUMBERS.every(Number.isInteger)) {
return new Error(`${propName} needs to be an array of two numbers`);
}
return null
}
This would throw an error if TWO_NUMBERS
isn't an array, isn't an array of two, and isn't an array of only integers.
You can get information about proptype functions here:
https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes
Its at the bottom of that example block.