I'm using the prop-types library in my React application and have the following situation:
MyComponent.propTypes = {
foo: PropTypes.arrayOf(
PropTypes.shape({
bar: PropTypes.string.isRequired,
baz: PropTypes.number.isRequired,
})
).isRequired
}
By setting isRequired
on foo
, foo
must be an array (not null/undefined). However, it is still allowed to be an empty array. In my case, I'd like to require the array to contain at least one element.
This is possible with a custom validator function:
MyComponent.propTypes = {
foo: function (props, propName, componentName) {
const val = props[propName]
if (!Array.isArray(val)) return new Error(`${propName} must be an array`)
if (val.length === 0) return new Error(`${propName} must have at least one element`)
val.forEach(function (elem) {
if (typeof elem.bar !== 'string') return new Error(`${propName}.bar must be a string`)
if (typeof elem.baz !== 'number') return new Error(`${propName}.baz must be a number`)
})
}
}
However, it isn't pretty, and feels like it could quickly get more complicated if the array contained larger + more complex objects.
Is there a cleaner way to achieve this?