8
votes

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:

  • prop value = string/number/object/etc --> no warning
  • prop value = null --> no warning
  • prop value = undefined (either explicitly or just omitting a prop value assignment) --> warning

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.

1
Have you ever considered to use TypeScript? It offers that out of the box at compile time, with the cost of having to tanspile the project.lilezek
I feel my question differs from the possible duplicate referenced above. The other person is like "why can't I do this? what's wrong?" and I'm like "how do I do this specific thing?" And it's not an acceptable answer for me to make a prop optional.Erik Hermansen
Re TypeScript, I appreciate the thought, but that solution can't be applied in my case.Erik Hermansen

1 Answers

6
votes

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)
};