Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom PropTypes that extend default PropTypes in react

I'm trying to create a custom PropType that checks if an array has numerical values and has a length of 2 (and there's some constraint on the ordering of the numbers).

Obviously I can do Array.PropType.arrayOf(Array.PropType.number) for the first two constraints.

I'd like to reuse this in my custom PropType (instead of rolling out my own numerical and array check).

How do I do that?

like image 786
praks5432 Avatar asked Oct 18 '22 16:10

praks5432


1 Answers

React.PropTypes.arrayOf( React.PropTypes.number ) just returns a function, so you can instead provide your own function to perform the validation.

Your function will be passed three parameters: props, propName, componentName

see the second to last example shown in React.PropTypes from the docs.

So a function that should satisfy your constraints would be:

function isTwoElementArrayOfNumbers( props, propName, componentName ){
  var _array = props[ propName ];

  if( _array && _array.constructor === Array && _array.length === 2 ){

    if( !_array.every(
      function isNumber( element ){
        return typeof element === 'number';
      })
    ){

      return new Error('elements must be numbers!');
    }
  }
  else{
    return new Error('2 element array of numbers not provided!');
  }
}

...in your react element
propTypes:{
  numArray: isTwoElementArrayOfNumbers
},
like image 71
sethro Avatar answered Oct 21 '22 07:10

sethro