Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs : how to check Proptypes with function and shape?

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.`
          );
        }
      }
like image 918
Zied Hf Avatar asked Sep 10 '25 16:09

Zied Hf


1 Answers

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

like image 175
Krasimir Avatar answered Sep 13 '25 05:09

Krasimir