I'm trying to create a proptype that can either be a string or an array with only 1 string and 1 object shape e.g. [10, { message: "hello world", type: "success" }]
Currently, I have:
static propTypes = {
myProp: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.string, myObjectShape])
),
]),
}
This will accept a string or an array that can have any amount of strings or object shapes. Is there a way to limit the array to only 1 string and 1 object shape?
You can create a custom prop type. Something along the lines of...
myProp: function(props, propName, componentName) {
if (!props[propName] || !props[propName].length !== 2) {
return new Error(`${propName} must be an array with length 2`);
}
if (typeof props[propName][0] !== 'string') {
return new Error(`The first element in ${propName} must be a string`);
}
// check for the shape of the object at index 1...
}
More about it here.