React.PropTypes.number float with min and max

All we need is an easy explanation of the problem, so here it is.

completed: React.PropTypes.number,

Can i specify a minimum and maximum to a number props in React component.

expected something like following:

completed: React.PropTypes.numberBetween(min, max),

I generate an array to specify the range

attempt:

completed: React.PropTypes.oneOf(Array.from({length: max -min+1, (v, k) => k + min})),

However , i want completed props to accept also float as well , whereas , it accepts only integer now .

How to make the following constraints combined :

  • prop is number ( integer, float, double,…any number)

  • between MIN and MAX

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can use Custom Validation.

completed: function(props, propName, componentName) {
   if(props[propName] < MIN || props[propName] > MAX) {
      return new Error('Invalid');
   }
}

Method 2

By writing a Custom Props Validator, u can achieve this. try this:

num: function(props, propName, componentName) {
    if(typeof props[propName] != 'number'){
      return new Error ('Invalid type of `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
    }else if (props[propName] < MIN || props[propName] > MAX) {
      return new Error('Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
    }
},

Method 3

I know this is an old post, but I thought I would share as I ran into this issue as well. All of the other answers address how to use this functionality for a single prop, but if you need this for multiple props, then creating a reusable PropType might be a better solution.

// Allow min/max values to be passed to PropType validator
export default const numberBetween = (min, max) => {
    // Return CustomProp to be executed
    return (props, propName, componentName) => {
        const prop = props[propName];
        if(typeof prop !== 'number' || prop < min || prop > max) {
            return new Error(`Prop ${propName} must be a number between ${min} and ${max} on ${componentName}`);
        }
    }
}

It is then used like this:

completed: numberBetween(1, 10)

Hope this helps someone!

Method 4

The CustomProp just like the Docs said:

completed: (props, propName, componentName) => 
             (props[propName] < MIN || props[propName] > MAX) && new Error('Invalid');

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply