Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React PropTypes: range of numbers

Is there a better way to validate if a number is inside a range?

Avoiding to write

PropTypes.oneOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 
like image 542
Pablo De Luca Avatar asked May 23 '18 13:05

Pablo De Luca


People also ask

Should you use PropTypes?

Props and PropTypes are important mechanisms for passing read-only attributes between React components. We can use React props, short for properties, to send data from one component to another. If a component receives the wrong type of props, it can cause bugs and unexpected errors in your app.

Can we use PropTypes in functional component?

In this example, we are using a class component, but the same functionality could also be applied to function components, or components created by React.memo or React.forwardRef . PropTypes exports a range of validators that can be used to make sure the data you receive is valid.

Should PropTypes be a dev dependency?

'prop-types' should be listed in the project's dependencies, not devDependencies.

How do you use PropTypes in a functional component React?

import React from 'react'; import PropTypes from 'prop-types'; function List(props) { const todos = props. todos. map((todo, index) => (<li key={index}>{todo}</li>)); return (<ul></ul>); } List. PropTypes = { todos: PropTypes.


2 Answers

According to the documentation, you can define your customProps

customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  }

So for your case you can try the following

function withinTen(props, propName, componentName) {
  componentName = comopnentName || 'ANONYMOUS';

  if (props[propName]) {
    let value = props[propName];
    if (typeof value === 'number') {
        return (value >= 1 && value <= 10) ? null : new Error(propName + ' in ' + componentName + " is not within 1 to 10");
    }
  }

  // assume all ok
  return null;
}


something.propTypes = {
  number: withinTen,
  content: React.PropTypes.node.isRequired
}
like image 107
Isaac Avatar answered Oct 19 '22 22:10

Isaac


You can use custom Prop validator.

completed: function(props, propName, componentName) {
    if (props[propName]>=1 &&  props[propName]<=10) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  }

Please refer the documentation for further details.

https://reactjs.org/docs/typechecking-with-proptypes.html

like image 45
Amit Avatar answered Oct 19 '22 23:10

Amit