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)
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.
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.
'prop-types' should be listed in the project's dependencies, not devDependencies.
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.
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With