Yoni Weisbrod
Yoni Weisbrod

Reputation: 117

Can I mix a type and a value in PropTypes oneOf?

Is it possible to use PropTypes.oneOf to enforce the presence of either a specific type or a string literal?

Example:

display: PropTypes.oneOf([PropTypes.bool, 'autohide']),

Or is it simply treating PropTypes.bool as whatever literal value it returns? Couldn't find any reference to this in the official documentation, so I'm assuming it doesn't work as I expect it to work. It doesn't raise an error, though.

Upvotes: 9

Views: 8174

Answers (2)

skyboyer
skyboyer

Reputation: 23763

You can nest oneOf() into oneOfType() like that

PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.oneOf(['autohide'])
])

Upvotes: 27

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

Yep, it's possible, but not directly. Actually you can have different PropTypes this way:

display: PropTypes.oneOf([
  true,
  false,
  'autohide'
]),

You know that the PropTypes.bool is going to be either true or false. For an advanced use of validation, see the CustomValidation here: customArrayProp.

Reference: Typechecking With PropTypes – React

Upvotes: 1

Related Questions