React.PropTypes array with a specific length

Can Rect.PropTypes be used to provide array length?

Here is a very simple case:

const TWO_NUMBERS = PropTypes.array; // i need this to be an array of two numbers

I know there are only objects in javascript arrays, so I tried this:

const TWO_NUMBERS = PropTypes.shape({
    0: PropTypes.number.isRequired,
    1: PropTypes.number.isRequired,
});

However, this continues to warn me expected an object but got an array.

+4
source share
4 answers

in this case, you will need to write your own special PropTypes function that responds to you.

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 will throw an error if TWO_NUMBERS is not an array, is not an array of two, and is not an array of integers only.

You can get information about proptype functions here:

https://facebook.imtqy.com/react/docs/typechecking-with-proptypes.html#react.proptypes

.

+6

.

  const propTypes = {
    TWO_NUMBERS: arrayOfLength.bind(null, 1),
  }

  const arrayOfLength = function(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.`
      );
    }
  },
+4

@finalfreq, . ( ) arrayOf(twoNumbers). , twoNumbers.isRequired ...

, , .

import invariant from 'invariant';

function isValid(value) {
  return Array.isArray(value) && value.length === 2 && value.every(Number.isFinite);
}

export default function twoNumbers(props, propName, componentName) {
  if (Array.isArray(props)) {
    props.forEach((item, index) => {
      invariant(
        isValid(item),
        `Array item index ${index} is ${item}, but needs to be an array of two numbers`
      );
    });
  }

  const value = props[propName];

  if (!value) return; // not required so could be null

  invariant(isValid(value), `${componentName} ${propName} needs to be an array of two numbers`);
}
+1

PropTypes . , PropTypes . PropTypes - .

-4

Source: https://habr.com/ru/post/1671752/


All Articles