Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React PropTypes: Allow different types of PropTypes for one prop

I have a component that receives a prop for its size. The prop can be either a string or a number ex: "LARGE" or 17.

Can I let React.PropTypes know that this can be either one or the other in the propTypes validation?

If I don't specify the type I get a warning:

prop type size is invalid; it must be a function, usually from React.PropTypes.

MyComponent.propTypes = {     size: React.PropTypes } 
like image 756
Kevin Amiranoff Avatar asked Jan 23 '17 14:01

Kevin Amiranoff


People also ask

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.

Are PropTypes necessary in React?

One of the most important things when building React application is to make sure that the components receive correct props. Passing wrong props leads to bugs and unexpected behavior, so it's a good idea to warn developers about this as early as possible.

How do you use PropTypes in a functional component React?

Using PropTypes in React PropTypes is React's internal mechanism for adding type checking to components. React components use a special property named propTypes to set up type checking. When props are passed to a React component, they are checked against the type definitions configured in the propTypes property.

Which method is used to do props validation by defining types to props?

propTypes is used for props validation in react component. When some of the props are passed with an invalid type, you will get the warnings on JavaScript console. After specifying the validation patterns, you will set the App.


2 Answers

size: PropTypes.oneOfType([   PropTypes.string,   PropTypes.number ]), 

Learn more: Typechecking With PropTypes

like image 57
Paweł Andruszków Avatar answered Sep 30 '22 22:09

Paweł Andruszków


For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([     PropTypes.number,     PropTypes.oneOf([ 'SMALL', 'LARGE' ]), ]), 
like image 37
cleong Avatar answered Oct 01 '22 00:10

cleong