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.
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)
};
Collected from the Internet
Please contact javaer1[email protected] to delete if infringement.
Comments