92490e2df21f3c27dae27a93a79f8b808fcf7eeb00f38256ae86a246b42eb3736908f1b3655788648d88928b893ab6726283fe1cac8d4e4f94044f1325c562 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # prop-types [![Build Status](https://travis-ci.com/facebook/prop-types.svg?branch=main)](https://travis-ci.org/facebook/prop-types)
  2. Runtime type checking for React props and similar objects.
  3. You can use prop-types to document the intended types of properties passed to
  4. components. React (and potentially other libraries—see the `checkPropTypes()`
  5. reference below) will check props passed to your components against those
  6. definitions, and warn in development if they don’t match.
  7. ## Installation
  8. ```shell
  9. npm install --save prop-types
  10. ```
  11. ## Importing
  12. ```js
  13. import PropTypes from 'prop-types'; // ES6
  14. var PropTypes = require('prop-types'); // ES5 with npm
  15. ```
  16. ### CDN
  17. If you prefer to exclude `prop-types` from your application and use it
  18. globally via `window.PropTypes`, the `prop-types` package provides
  19. single-file distributions, which are hosted on the following CDNs:
  20. * [**unpkg**](https://unpkg.com/prop-types/)
  21. ```html
  22. <!-- development version -->
  23. <script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script>
  24. <!-- production version -->
  25. <script src="https://unpkg.com/prop-types@15.6/prop-types.min.js"></script>
  26. ```
  27. * [**cdnjs**](https://cdnjs.com/libraries/prop-types)
  28. ```html
  29. <!-- development version -->
  30. <script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
  31. <!-- production version -->
  32. <script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
  33. ```
  34. To load a specific version of `prop-types` replace `15.6.0` with the version number.
  35. ## Usage
  36. PropTypes was originally exposed as part of the React core module, and is
  37. commonly used with React components.
  38. Here is an example of using PropTypes with a React component, which also
  39. documents the different validators provided:
  40. ```js
  41. import React from 'react';
  42. import PropTypes from 'prop-types';
  43. class MyComponent extends React.Component {
  44. render() {
  45. // ... do things with the props
  46. }
  47. }
  48. MyComponent.propTypes = {
  49. // You can declare that a prop is a specific JS primitive. By default, these
  50. // are all optional.
  51. optionalArray: PropTypes.array,
  52. optionalBigInt: PropTypes.bigint,
  53. optionalBool: PropTypes.bool,
  54. optionalFunc: PropTypes.func,
  55. optionalNumber: PropTypes.number,
  56. optionalObject: PropTypes.object,
  57. optionalString: PropTypes.string,
  58. optionalSymbol: PropTypes.symbol,
  59. // Anything that can be rendered: numbers, strings, elements or an array
  60. // (or fragment) containing these types.
  61. // see https://reactjs.org/docs/rendering-elements.html for more info
  62. optionalNode: PropTypes.node,
  63. // A React element (ie. <MyComponent />).
  64. optionalElement: PropTypes.element,
  65. // A React element type (eg. MyComponent).
  66. // a function, string, or "element-like" object (eg. React.Fragment, Suspense, etc.)
  67. // see https://github.com/facebook/react/blob/HEAD/packages/shared/isValidElementType.js
  68. optionalElementType: PropTypes.elementType,
  69. // You can also declare that a prop is an instance of a class. This uses
  70. // JS's instanceof operator.
  71. optionalMessage: PropTypes.instanceOf(Message),
  72. // You can ensure that your prop is limited to specific values by treating
  73. // it as an enum.
  74. optionalEnum: PropTypes.oneOf(['News', 'Photos']),
  75. // An object that could be one of many types
  76. optionalUnion: PropTypes.oneOfType([
  77. PropTypes.string,
  78. PropTypes.number,
  79. PropTypes.instanceOf(Message)
  80. ]),
  81. // An array of a certain type
  82. optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
  83. // An object with property values of a certain type
  84. optionalObjectOf: PropTypes.objectOf(PropTypes.number),
  85. // You can chain any of the above with `isRequired` to make sure a warning
  86. // is shown if the prop isn't provided.
  87. // An object taking on a particular shape
  88. optionalObjectWithShape: PropTypes.shape({
  89. optionalProperty: PropTypes.string,
  90. requiredProperty: PropTypes.number.isRequired
  91. }),
  92. // An object with warnings on extra properties
  93. optionalObjectWithStrictShape: PropTypes.exact({
  94. optionalProperty: PropTypes.string,
  95. requiredProperty: PropTypes.number.isRequired
  96. }),
  97. requiredFunc: PropTypes.func.isRequired,
  98. // A value of any data type
  99. requiredAny: PropTypes.any.isRequired,
  100. // You can also specify a custom validator. It should return an Error
  101. // object if the validation fails. Don't `console.warn` or throw, as this
  102. // won't work inside `oneOfType`.
  103. customProp: function(props, propName, componentName) {
  104. if (!/matchme/.test(props[propName])) {
  105. return new Error(
  106. 'Invalid prop `' + propName + '` supplied to' +
  107. ' `' + componentName + '`. Validation failed.'
  108. );
  109. }
  110. },
  111. // You can also supply a custom validator to `arrayOf` and `objectOf`.
  112. // It should return an Error object if the validation fails. The validator
  113. // will be called for each key in the array or object. The first two
  114. // arguments of the validator are the array or object itself, and the
  115. // current item's key.
  116. customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
  117. if (!/matchme/.test(propValue[key])) {
  118. return new Error(
  119. 'Invalid prop `' + propFullName + '` supplied to' +
  120. ' `' + componentName + '`. Validation failed.'
  121. );
  122. }
  123. })
  124. };
  125. ```
  126. Refer to the [React documentation](https://facebook.github.io/react/docs/typechecking-with-proptypes.html) for more information.
  127. ## Migrating from React.PropTypes
  128. Check out [Migrating from React.PropTypes](https://facebook.github.io/react/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) for details on how to migrate to `prop-types` from `React.PropTypes`.
  129. Note that this blog posts **mentions a codemod script that performs the conversion automatically**.
  130. There are also important notes below.
  131. ## How to Depend on This Package?
  132. For apps, we recommend putting it in `dependencies` with a caret range.
  133. For example:
  134. ```js
  135. "dependencies": {
  136. "prop-types": "^15.5.7"
  137. }
  138. ```
  139. For libraries, we *also* recommend leaving it in `dependencies`:
  140. ```js
  141. "dependencies": {
  142. "prop-types": "^15.5.7"
  143. },
  144. "peerDependencies": {
  145. "react": "^15.5.0"
  146. }
  147. ```
  148. **Note:** there are known issues in versions before 15.5.7 so we recommend using it as the minimal version.
  149. Make sure that the version range uses a caret (`^`) and thus is broad enough for npm to efficiently deduplicate packages.
  150. For UMD bundles of your components, make sure you **don’t** include `PropTypes` in the build. Usually this is done by marking it as an external (the specifics depend on your bundler), just like you do with React.
  151. ## Compatibility
  152. ### React 0.14
  153. This package is compatible with **React 0.14.9**. Compared to 0.14.8 (which was released in March of 2016), there are no other changes in 0.14.9, so it should be a painless upgrade.
  154. ```shell
  155. # ATTENTION: Only run this if you still use React 0.14!
  156. npm install --save react@^0.14.9 react-dom@^0.14.9
  157. ```
  158. ### React 15+
  159. This package is compatible with **React 15.3.0** and higher.
  160. ```
  161. npm install --save react@^15.3.0 react-dom@^15.3.0
  162. ```
  163. ### What happens on other React versions?
  164. It outputs warnings with the message below even though the developer doesn’t do anything wrong. Unfortunately there is no solution for this other than updating React to either 15.3.0 or higher, or 0.14.9 if you’re using React 0.14.
  165. ## Difference from `React.PropTypes`: Don’t Call Validator Functions
  166. First of all, **which version of React are you using**? You might be seeing this message because a component library has updated to use `prop-types` package, but your version of React is incompatible with it. See the [above section](#compatibility) for more details.
  167. Are you using either React 0.14.9 or a version higher than React 15.3.0? Read on.
  168. When you migrate components to use the standalone `prop-types`, **all validator functions will start throwing an error if you call them directly**. This makes sure that nobody relies on them in production code, and it is safe to strip their implementations to optimize the bundle size.
  169. Code like this is still fine:
  170. ```js
  171. MyComponent.propTypes = {
  172. myProp: PropTypes.bool
  173. };
  174. ```
  175. However, code like this will not work with the `prop-types` package:
  176. ```js
  177. // Will not work with `prop-types` package!
  178. var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop');
  179. ```
  180. It will throw an error:
  181. ```
  182. Calling PropTypes validators directly is not supported by the `prop-types` package.
  183. Use PropTypes.checkPropTypes() to call them.
  184. ```
  185. (If you see **a warning** rather than an error with this message, please check the [above section about compatibility](#compatibility).)
  186. This is new behavior, and you will only encounter it when you migrate from `React.PropTypes` to the `prop-types` package. For the vast majority of components, this doesn’t matter, and if you didn’t see [this warning](https://facebook.github.io/react/warnings/dont-call-proptypes.html) in your components, your code is safe to migrate. This is not a breaking change in React because you are only opting into this change for a component by explicitly changing your imports to use `prop-types`. If you temporarily need the old behavior, you can keep using `React.PropTypes` until React 16.
  187. **If you absolutely need to trigger the validation manually**, call `PropTypes.checkPropTypes()`. Unlike the validators themselves, this function is safe to call in production, as it will be replaced by an empty function:
  188. ```js
  189. // Works with standalone PropTypes
  190. PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent');
  191. ```
  192. See below for more info.
  193. **If you DO want to use validation in production**, you can choose to use the **development version** by importing/requiring `prop-types/prop-types` instead of `prop-types`.
  194. **You might also see this error** if you’re calling a `PropTypes` validator from your own custom `PropTypes` validator. In this case, the fix is to make sure that you are passing *all* of the arguments to the inner function. There is a more in-depth explanation of how to fix it [on this page](https://facebook.github.io/react/warnings/dont-call-proptypes.html#fixing-the-false-positive-in-third-party-proptypes). Alternatively, you can temporarily keep using `React.PropTypes` until React 16, as it would still only warn in this case.
  195. If you use a bundler like Browserify or Webpack, don’t forget to [follow these instructions](https://reactjs.org/docs/optimizing-performance.html#use-the-production-build) to correctly bundle your application in development or production mode. Otherwise you’ll ship unnecessary code to your users.
  196. ## PropTypes.checkPropTypes
  197. React will automatically check the propTypes you set on the component, but if
  198. you are using PropTypes without React then you may want to manually call
  199. `PropTypes.checkPropTypes`, like so:
  200. ```js
  201. const myPropTypes = {
  202. name: PropTypes.string,
  203. age: PropTypes.number,
  204. // ... define your prop validations
  205. };
  206. const props = {
  207. name: 'hello', // is valid
  208. age: 'world', // not valid
  209. };
  210. // Let's say your component is called 'MyComponent'
  211. // Works with standalone PropTypes
  212. PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
  213. // This will warn as follows:
  214. // Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
  215. // `MyComponent`, expected `number`.
  216. ```
  217. ## PropTypes.resetWarningCache()
  218. `PropTypes.checkPropTypes(...)` only `console.error`s a given message once. To reset the error warning cache in tests, call `PropTypes.resetWarningCache()`
  219. ### License
  220. prop-types is [MIT licensed](./LICENSE).