Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 348
Yoni Weisbrod Avatar asked Jan 21 '19 13:01

Yoni Weisbrod


People also ask

Can we use PropTypes in functional component?

Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.

Is PropTypes deprecated?

5 PropTypes are deprecated in the React package and have been given a package of their own. Change is an inevitable part of life. The upshot is twofold. 1) If you use another type-checking mechanism, you don't have to worry about shipping unnecessary bulk to your end users.

Do I need PropTypes with TypeScript?

Props are required in TypeScript In the prop-types package, all props are optional by default. To make a prop required, you will have to use . isRequired explicitly. With TypeScript, that is not the case.

What does the PropTypes check do for the component?

What are PropTypes? PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.


2 Answers

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

PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.oneOf(['autohide'])
])
like image 80
skyboyer Avatar answered Oct 10 '22 21:10

skyboyer


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

like image 39
Praveen Kumar Purushothaman Avatar answered Oct 10 '22 21:10

Praveen Kumar Purushothaman