UNPKG

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