Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify proptypes to allow nullable, required prop value?

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.

like image 236
Erik Hermansen Avatar asked Oct 19 '17 21:10

Erik Hermansen


People also ask

How do you define an object in PropTypes?

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.

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 I use PropTypes or TypeScript?

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.

What is the difference between flow and PropTypes?

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.


1 Answers

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)
};
like image 61
Alex Guerra Avatar answered Oct 18 '22 17:10

Alex Guerra