How to specify null prop type in ReactJS?

user1261710 picture user1261710 · Nov 21, 2016 · Viewed 24.7k times · Source

I've got a prop on a ReactJS Component that's either null or an Immutable Map.

At the bottom of my widget if I write:

MyComponent.propTypes = {
    myMap: React.PropTypes.instanceOf(Immutable.Map)
};

I am leaving this open to the possibility of being null, undefined, or a Map.

How can I make this required and of type null or map only?

https://facebook.github.io/react/docs/typechecking-with-proptypes.html

I see this example but I do not know how to tailor the syntax to my needs or if it is even possible.

Edit: If a property is null, then it is still there but undefined means that it's not been included altogether.

For example:

<Component id={1} data={null} />
<Component id={2} data={Immutable.Map()} />
<Component id={3} />

Answer

Lars Nystr&#246;m picture Lars Nyström · Oct 30, 2018

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.