UNPKG

11.2 kBMarkdownView Raw
1# prop-types [![Build Status](https://travis-ci.com/facebook/prop-types.svg?branch=master)](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 optionalBool: PropTypes.bool,
71 optionalFunc: PropTypes.func,
72 optionalNumber: PropTypes.number,
73 optionalObject: PropTypes.object,
74 optionalString: PropTypes.string,
75 optionalSymbol: PropTypes.symbol,
76
77 // Anything that can be rendered: numbers, strings, elements or an array
78 // (or fragment) containing these types.
79 optionalNode: PropTypes.node,
80
81 // A React element (ie. <MyComponent />).
82 optionalElement: PropTypes.element,
83
84 // A React element type (ie. MyComponent).
85 optionalElementType: PropTypes.elementType,
86
87 // You can also declare that a prop is an instance of a class. This uses
88 // JS's instanceof operator.
89 optionalMessage: PropTypes.instanceOf(Message),
90
91 // You can ensure that your prop is limited to specific values by treating
92 // it as an enum.
93 optionalEnum: PropTypes.oneOf(['News', 'Photos']),
94
95 // An object that could be one of many types
96 optionalUnion: PropTypes.oneOfType([
97 PropTypes.string,
98 PropTypes.number,
99 PropTypes.instanceOf(Message)
100 ]),
101
102 // An array of a certain type
103 optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
104
105 // An object with property values of a certain type
106 optionalObjectOf: PropTypes.objectOf(PropTypes.number),
107
108 // You can chain any of the above with `isRequired` to make sure a warning
109 // is shown if the prop isn't provided.
110
111 // An object taking on a particular shape
112 optionalObjectWithShape: PropTypes.shape({
113 optionalProperty: PropTypes.string,
114 requiredProperty: PropTypes.number.isRequired
115 }),
116
117 // An object with warnings on extra properties
118 optionalObjectWithStrictShape: PropTypes.exact({
119 optionalProperty: PropTypes.string,
120 requiredProperty: PropTypes.number.isRequired
121 }),
122
123 requiredFunc: PropTypes.func.isRequired,
124
125 // A value of any data type
126 requiredAny: PropTypes.any.isRequired,
127
128 // You can also specify a custom validator. It should return an Error
129 // object if the validation fails. Don't `console.warn` or throw, as this
130 // won't work inside `oneOfType`.
131 customProp: function(props, propName, componentName) {
132 if (!/matchme/.test(props[propName])) {
133 return new Error(
134 'Invalid prop `' + propName + '` supplied to' +
135 ' `' + componentName + '`. Validation failed.'
136 );
137 }
138 },
139
140 // You can also supply a custom validator to `arrayOf` and `objectOf`.
141 // It should return an Error object if the validation fails. The validator
142 // will be called for each key in the array or object. The first two
143 // arguments of the validator are the array or object itself, and the
144 // current item's key.
145 customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
146 if (!/matchme/.test(propValue[key])) {
147 return new Error(
148 'Invalid prop `' + propFullName + '` supplied to' +
149 ' `' + componentName + '`. Validation failed.'
150 );
151 }
152 })
153};
154```
155
156Refer to the [React documentation](https://facebook.github.io/react/docs/typechecking-with-proptypes.html) for more information.
157
158## Migrating from React.PropTypes
159
160Check 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`.
161
162Note that this blog posts **mentions a codemod script that performs the conversion automatically**.
163
164There are also important notes below.
165
166## How to Depend on This Package?
167
168For apps, we recommend putting it in `dependencies` with a caret range.
169For example:
170
171```js
172 "dependencies": {
173 "prop-types": "^15.5.7"
174 }
175```
176
177For libraries, we *also* recommend leaving it in `dependencies`:
178
179```js
180 "dependencies": {
181 "prop-types": "^15.5.7"
182 },
183 "peerDependencies": {
184 "react": "^15.5.0"
185 }
186```
187
188**Note:** there are known issues in versions before 15.5.7 so we recommend using it as the minimal version.
189
190Make sure that the version range uses a caret (`^`) and thus is broad enough for npm to efficiently deduplicate packages.
191
192For 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.
193
194## Compatibility
195
196### React 0.14
197
198This 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.
199
200```shell
201# ATTENTION: Only run this if you still use React 0.14!
202npm install --save react@^0.14.9 react-dom@^0.14.9
203```
204
205### React 15+
206
207This package is compatible with **React 15.3.0** and higher.
208
209```
210npm install --save react@^15.3.0 react-dom@^15.3.0
211```
212
213### What happens on other React versions?
214
215It 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.
216
217## Difference from `React.PropTypes`: Don’t Call Validator Functions
218
219First 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.
220
221Are you using either React 0.14.9 or a version higher than React 15.3.0? Read on.
222
223When 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.
224
225Code like this is still fine:
226
227```js
228MyComponent.propTypes = {
229 myProp: PropTypes.bool
230};
231```
232
233However, code like this will not work with the `prop-types` package:
234
235```js
236// Will not work with `prop-types` package!
237var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop');
238```
239
240It will throw an error:
241
242```
243Calling PropTypes validators directly is not supported by the `prop-types` package.
244Use PropTypes.checkPropTypes() to call them.
245```
246
247(If you see **a warning** rather than an error with this message, please check the [above section about compatibility](#compatibility).)
248
249This 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.
250
251**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:
252
253```js
254// Works with standalone PropTypes
255PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent');
256```
257See below for more info.
258
259**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.
260
261If 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.
262
263## PropTypes.checkPropTypes
264
265React will automatically check the propTypes you set on the component, but if
266you are using PropTypes without React then you may want to manually call
267`PropTypes.checkPropTypes`, like so:
268
269```js
270const myPropTypes = {
271 name: PropTypes.string,
272 age: PropTypes.number,
273 // ... define your prop validations
274};
275
276const props = {
277 name: 'hello', // is valid
278 age: 'world', // not valid
279};
280
281// Let's say your component is called 'MyComponent'
282
283// Works with standalone PropTypes
284PropTypes.checkPropTypes(myPropTypes, props, 'age', 'MyComponent');
285// This will warn as follows:
286// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
287// `MyComponent`, expected `number`.
288```
289
290## PropTypes.resetWarningCache()
291
292`PropTypes.checkPropTypes(...)` only `console.error.log(...)`s a given message once. To reset the cache while testing call `PropTypes.resetWarningCache()`
293
294### License
295
296prop-types is [MIT licensed](./LICENSE).