How to specify null prop type in ReactJS? How to specify null prop type in ReactJS? javascript javascript

How to specify null prop type in ReactJS?


It is possible to use PropTypes.oneOf([null]).isRequired. It should allow null, and nothing else. You can combine that with any other type:

PropTypes.oneOfType([  PropTypes.string.isRequired,  PropTypes.oneOf([null]).isRequired,]).isRequired

Edit: I just had this prop type fail for me when given a null prop using prop-types 15.7.2, so I'm not sure this works anymore (if it ever did?). I reverted to allowing both undefineds and nulls by just not using isRequired.


I had similar problem and that's how I got here. I found a solution that's good enough for me, so I might as well share it.

In short, I removed .isRequired and set defaultProps to null.

I wanted something like this:

// this won't work, because `PropTypes.null` doesn't exists!MyComponent.propTypes = {  item: PropTypes.oneOfType([ItemPropTypesShape, PropTypes.null]).isRequired,};// this also won't work!MyComponent.propTypes = {  item: PropTypes.oneOfType([ItemPropTypesShape, PropTypes.instanceOf(null)]).isRequired,};

The null is always treated as error when prop is required.

I ended up doing this:

MyComponent.propTypes = {  item: ItemPropTypesShape,};MyComponent.defaultProps = {  item: null,};

If PropTypes is all we have, this works for me!


This requirement seems to be unsupported with the current version of React.

Refer to React issue #2166 for more details. This issue discusses the possibility of an isRequiredOrNull property in addition to isRequired. Bottom line:

I wouldn't expect there to be further changes to PropTypes. Flow has become much more mature recently, and from what I heard from the React team, it is the longer term solution to type checking. This puts PropTypes into the same "compatibility" bucket in terms of priorities—like createClass or React addons, they are still supported, but only with bugfixes and performance improvements, without adding new features or changing the API.

In other words, if you require more sophisticated type checking, use Flow instead.