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 }
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.
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.
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.
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.
size: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]),
Learn more: Typechecking With PropTypes
For documentation purpose, it's better to list the string values that are legal:
size: PropTypes.oneOfType([ PropTypes.number, PropTypes.oneOf([ 'SMALL', 'LARGE' ]), ]),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With