Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.PropTypes array with specific length

Is it possible to use React.PropTypes to enforce length's on an array?

Here is a very simple case:

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

I know in javascript arrays are just objects so I tried this:

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

However this keeps telling warning me expected an object but got an array.

like image 745
Noitidart Avatar asked Mar 07 '17 22:03

Noitidart


1 Answers

In this case you would need to write your own special PropTypes function which react provides you to do.

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 would throw an error if TWO_NUMBERS isn't an array, isn't an array of two, and isn't an array of only integers.

You can get information about proptype functions here:

https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes

Its at the bottom of that example block.

like image 94
finalfreq Avatar answered Sep 30 '22 19:09

finalfreq