40

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} />
3

8 Answers 8

22

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.

2
  • This worked for me using numbers in create react app > react-scripts 3.4.1
    – Shane
    Jul 13, 2020 at 20:07
  • worked for me only without the .isRequired
    – oriadam
    Apr 23 at 14:21
14

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!

0
11

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.

1
  • 1
    In 2021, Flow is on the way out in favor of TypeScript.
    – Slbox
    Sep 16, 2021 at 19:14
5

Seems like PropTypes.instanceOf(null) works.

2
  • TS2345: Argument of type 'null' is not assignable to parameter of type 'new (...args: any[]) => {}'.
    – Simon
    Mar 3, 2020 at 22:29
  • 1
    Warning: Failed prop type: Right-hand side of 'instanceof' is not an object Doesn't work on React 16.8 with prop-types 15.7 so I'm doubting this on 15.6
    – Jeff Klink
    May 28, 2020 at 18:51
3

You can use the prop type without .isRequired.

MyComponent.propTypes = {
    name: PropTypes.string
}

And define the null value in the defaultProps

MyComponent.defaultProps = {
    name: null
}
1
  • 2
    You made a mistake in second snippet, remove propTypes to defaultProps May 13, 2021 at 15:31
2

Maybe too late but this work for me, is a custom propType. More info in react docs: https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes

static propTypes = {
  myMap: function(props, propName, componentName) {
    if (props[propName] !== null && !(props[propName] instanceof Immutable.Map)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to `' + componentName + '`. Expected null or Immutable.Map, but received ' + typeof props[propName] + '. Validation failed.'
      )
    }
  },
}
0
0

To help with this quite common issue, I created a clean and fully-typed wrapper called better-prop-types:

import BetterPropTypes from 'better-prop-types'

// ...

MyComponent.propTypes = {
  myMap: BetterPropTypes.PropTypes.instanceOf(Immutable.Map).isRequiredButNullable
}
0
PropTypes.shape({ current: PropTypes.object })
2
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Oct 26, 2022 at 2:03
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – nima
    Oct 30, 2022 at 7:39

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.