I have an array with this shape :
dataSource: PropTypes.arrayOf(
        PropTypes.shape({
          share: PropTypes.number,
          visibleInLegend: PropTypes.bool,
          order: PropTypes.number,
          color: PropTypes.string
        })
Now, I want to limit the lenght to be only 2. I replaced the last proptype with a function like this :
dataSource: function(props, propName, componentName) {
    let arrayPropLength = props[propName].length;
    if (arrayPropLength !== 2) {
      return new Error(
        `Invalid array length ${arrayPropLength} (expected 2 for prop ${propName} supplied to ${componentName}. Validation failed.`
      );
    }
  }
The two checks work fine, however this will test only the length of array and I want to combine both of them into a function ? to be something like this :
dataSource: function(props, propName, componentName) {
props[propName].PropTypes.shape({
              share: PropTypes.number,
              visibleInLegend: PropTypes.bool,
              order: PropTypes.number,
              color: PropTypes.string
            })
        let arrayPropLength = props[propName].length;
        if (arrayPropLength !== 2) {
          return new Error(
            `Invalid array length ${arrayPropLength} (expected 2 for prop ${propName} supplied to ${componentName}. Validation failed.`
          );
        }
      }
I think checkPropTypes API may be used in this case. You keep your custom function but you also run checkPropTypes one.
const myPropTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  // ... define your prop validations
};
const props = {
  name: 'hello', // is valid
  age: 'world', // not valid
};
// Let's say your component is called 'MyComponent'
// Works with standalone PropTypes
PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
// This will warn as follows:
// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
// `MyComponent`, expected `number`.
From the official doc here https://github.com/facebook/prop-types#proptypescheckproptypes
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