For my project, it's desirable to pass the null value in component props to indicate an unspecified value (a "known unknown", if you will). It's our team's convention to use null this way.
Via component propTypes definitions, I would like to require a value be passed for a prop, yet allow it to be null (not undefined) without React prop type validation firing a warning.
So to restate that in an i/o style:
How can this behavior be accomplished?
One idea is to write some alternative to .isRequired, like .isDefined that won't fire a warning for a null value, but I don't see how to do this without forking or abandoning the prop-types library.
propTypes = { //// key is the name of the prop and // value is the PropType } export default Count; PropTypes are also objects with a key and a value pair where the 'key' is the name of the prop while the value represents the type or class by which they are defined.
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.
PropTypes does type-checking during runtime while the application is running in the browser. However, TypeScript does type-checking during compile time when the TypeScript code is compiled to JavaScript. This is worth noting because it influences how the tools can be used.
Flow is a static analysis tool which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time. PropTypes is a basic type checker which has been patched onto React.
I'm not sure if you could get it working in a chainable way (I've thought about it for maybe two minutes), but maybe you could use a custom validator?
function allowNull(wrappedPropTypes) {
return (props, propName, ...rest) => {
if (props[propName] === null) return null;
return wrappedPropTypes(props, propName, ...rest);
}
}
MyComponent.propTypes = {
nullOrNumber: allowNull(PropTypes.number.isRequired)
};
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