5

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?

2 Answers 2

3

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
},
Sign up to request clarification or add additional context in comments.

2 Comments

Attempting to do this fires a warning in React 15.3.x: facebook.github.io/react/warnings/dont-call-proptypes.html
@ConAntonakos: to be more specific, in React 15, the first solution in my answer (reusing PropType's arrayOf) became problematic. My actual suggested solution (writing your own simple function to check the prop) is perfectly valid and still works fine.
0

I don't know about extending them, I'm not sure that's possible.

But you could store the above as an exported constant and use it to compose properties of other propTypes (but I think you probably already know this):

export const CustomProp = Array.PropType.arrayOf(Array.PropType.number)

export const OtherCustomProp = contains({
 foo: React.PropTypes.string,
 bars: CustomProp
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.