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.

Leave a Comment