UNPKG

11.7 kBMarkdownView Raw
1# prop-types [![Build Status](https://travis-ci.com/facebook/prop-types.svg?branch=main)](https://travis-ci.org/facebook/prop-types)
2
3Runtime type checking for React props and similar objects.
4
5You can use prop-types to document the intended types of properties passed to
6components. React (and potentially other libraries—see the `checkPropTypes()`
7reference below) will check props passed to your components against those
8definitions, and warn in development if they don’t match.
9
10## Installation
11
12```shell
13npm install --save prop-types
14```
15
16## Importing
17
18```js
19import PropTypes from 'prop-types'; // ES6
20var PropTypes = require('prop-types'); // ES5 with npm
21```
22
23### CDN
24
25If you prefer to exclude `prop-types` from your application and use it
26globally via `window.PropTypes`, the `prop-types` package provides
27single-file distributions, which are hosted on the following CDNs:
28
29* [**unpkg**](https://unpkg.com/prop-types/)
30```html
31<!-- development version -->
32<script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script>
33
34<!-- production version -->
35<script src="https://unpkg.com/prop-types@15.6/prop-types.min.js"></script>
36```
37
38* [**cdnjs**](https://cdnjs.com/libraries/prop-types)
39```html
40<!-- development version -->
41<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
42
43<!-- production version -->
44<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
45```
46
47To load a specific version of `prop-types` replace `15.6.0` with the version number.
48
49## Usage
50
51PropTypes was originally exposed as part of the React core module, and is
52commonly used with React components.
53Here is an example of using PropTypes with a React component, which also
54documents the different validators provided:
55
56```js
57import React from 'react';
58import PropTypes from 'prop-types';
59
60class MyComponent extends React.Component {
61 render() {
62 // ... do things with the props
63 }
64}
65
66MyComponent.propTypes = {
67 // You can declare that a prop is a specific JS primitive. By default, these
68 // are all optional.
69 optionalArray: PropTypes.array,
70 optionalBigInt: PropTypes.bigint,
71 optionalBool: PropTypes.bool,
72 optionalFunc: PropTypes.func,
73 optionalNumber: PropTypes.number,
74 optionalObject: PropTypes.object,
75 optionalString: PropTypes.string,
76 optionalSymbol: PropTypes.symbol,
77
78 // Anything that can be rendered: numbers, strings, elements or an array
79 // (or fragment) containing these types.
80 // see https://reactjs.org/docs/rendering-elements.html for more info
81 optionalNode: PropTypes.node,
82
83 // A React element (ie. <MyComponent />).
84 optionalElement: PropTypes.element,
85
86 // A React element type (eg. MyComponent).
87 // a function, string, or "element-like" object (eg. React.Fragment, Suspense, etc.)
88 // see https://github.com/facebook/react/blob/HEAD/packages/shared/isValidElementType.js
89 optionalElementType: PropTypes.elementType,
90
91 // You can also declare that a prop is an instance of a class. This uses
92 // JS's instanceof operator.
93 optionalMessage: PropTypes.instanceOf(Message),
94
95 // You can ensure that your prop is limited to specific values by treating
96 // it as an enum.
97 optionalEnum: PropTypes.oneOf(['News', 'Photos']),
98
99 // An object that could be one of many types
100 optionalUnion: PropTypes.oneOfType([
101 PropTypes.string,
102 PropTypes.number,
103 PropTypes.instanceOf(Message)
104 ]),
105
106 // An array of a certain type
107 optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
108
109 // An object with property values of a certain type
110 optionalObjectOf: PropTypes.objectOf(PropTypes.number),
111
112 // You can chain any of the above with `isRequired` to make sure a warning
113 // is shown if the prop isn't provided.
114
115 // An object taking on a particular shape
116 optionalObjectWithShape: PropTypes.shape({
117 optionalProperty: PropTypes.string,
118 requiredProperty: PropTypes.number.isRequired
119 }),
120
121 // An object with warnings on extra properties
122 optionalObjectWithStrictShape: PropTypes.exact({
123 optionalProperty: PropTypes.string,
124 requiredProperty: PropTypes.number.isRequired
125 }),
126
127 requiredFunc: PropTypes.func.isRequired,
128
129 // A value of any data type
130 requiredAny: PropTypes.any.isRequired,
131
132 // You can also specify a custom validator. It should return an Error
133 // object if the validation fails. Don't `console.warn` or throw, as this
134 // won't work inside `oneOfType`.
135 customProp: function(props, propName, componentName) {
136 if (!/matchme/.test(props[propName])) {
137 return new Error(
138 'Invalid prop `' + propName + '` supplied to' +
139 ' `' + componentName + '`. Validation failed.'
140 );
141 }
142 },
143
144 // You can also supply a custom validator to `arrayOf` and `objectOf`.
145 // It should return an Error object if the validation fails. The validator
146 // will be called for each key in the array or object. The first two
147 // arguments of the validator are the array or object itself, and the
148 // current item's key.
149 customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
150 if (!/matchme/.test(propValue[key])) {
151 return new Error(
152 'Invalid prop `' + propFullName + '` supplied to' +
153 ' `' + componentName + '`. Validation failed.'
154 );
155 }
156 })
157};
158```
159
160Refer to the [React documentation](https://facebook.github.io/react/docs/typechecking-with-proptypes.html) for more information.
161
162## Migrating from React.PropTypes
163
164Check 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`.
165
166Note that this blog posts **mentions a codemod script that performs the conversion automatically**.
167
168There are also important notes below.
169
170## How to Depend on This Package?
171
172For apps, we recommend putting it in `dependencies` with a caret range.
173For example:
174
175```js
176 "dependencies": {
177 "prop-types": "^15.5.7"
178 }
179```
180
181For libraries, we *also* recommend leaving it in `dependencies`:
182
183```js
184 "dependencies": {
185 "prop-types": "^15.5.7"
186 },
187 "peerDependencies": {
188 "react": "^15.5.0"
189 }
190```
191
192**Note:** there are known issues in versions before 15.5.7 so we recommend using it as the minimal version.
193
194Make sure that the version range uses a caret (`^`) and thus is broad enough for npm to efficiently deduplicate packages.
195
196For 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.
197
198## Compatibility
199
200### React 0.14
201
202This 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.
203
204```shell
205# ATTENTION: Only run this if you still use React 0.14!
206npm install --save react@^0.14.9 react-dom@^0.14.9
207```
208
209### React 15+
210
211This package is compatible with **React 15.3.0** and higher.
212
213```
214npm install --save react@^15.3.0 react-dom@^15.3.0
215```
216
217### What happens on other React versions?
218
219It 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.
220
221## Difference from `React.PropTypes`: Don’t Call Validator Functions
222
223First 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.
224
225Are you using either React 0.14.9 or a version higher than React 15.3.0? Read on.
226
227When 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.
228
229Code like this is still fine:
230
231```js
232MyComponent.propTypes = {
233 myProp: PropTypes.bool
234};
235```
236
237However, code like this will not work with the `prop-types` package:
238
239```js
240// Will not work with `prop-types` package!
241var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop');
242```
243
244It will throw an error:
245
246```
247Calling PropTypes validators directly is not supported by the `prop-types` package.
248Use PropTypes.checkPropTypes() to call them.
249```
250
251(If you see **a warning** rather than an error with this message, please check the [above section about compatibility](#compatibility).)
252
253This 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.
254
255**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:
256
257```js
258// Works with standalone PropTypes
259PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent');
260```
261See below for more info.
262
263**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`.
264
265**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.
266
267If 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.
268
269## PropTypes.checkPropTypes
270
271React will automatically check the propTypes you set on the component, but if
272you are using PropTypes without React then you may want to manually call
273`PropTypes.checkPropTypes`, like so:
274
275```js
276const myPropTypes = {
277 name: PropTypes.string,
278 age: PropTypes.number,
279 // ... define your prop validations
280};
281
282const props = {
283 name: 'hello', // is valid
284 age: 'world', // not valid
285};
286
287// Let's say your component is called 'MyComponent'
288
289// Works with standalone PropTypes
290PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
291// This will warn as follows:
292// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
293// `MyComponent`, expected `number`.
294```
295
296## PropTypes.resetWarningCache()
297
298`PropTypes.checkPropTypes(...)` only `console.error`s a given message once. To reset the error warning cache in tests, call `PropTypes.resetWarningCache()`
299
300### License
301
302prop-types is [MIT licensed](./LICENSE).