prop-types

Runtime type checking for React props and similar objects.

You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match.

Installation

  1. npm install --save prop-types

Importing

  1. import PropTypes from 'prop-types'; // ES6
  2. var PropTypes = require('prop-types'); // ES5 with npm

CDN

If you prefer to exclude prop-types from your application and use it globally via window.PropTypes, the prop-types package provides single-file distributions, which are hosted on the following CDNs:

``` * [**cdnjs**](https://cdnjs.com/libraries/prop-types) ```html

  1. To load a specific version of `prop-types` replace `15.6.0` with the version number.
  2. ## Usage
  3. PropTypes was originally exposed as part of the React core module, and is
  4. commonly used with React components.
  5. Here is an example of using PropTypes with a React component, which also
  6. documents the different validators provided:
  7. ```js
  8. import React from 'react';
  9. import PropTypes from 'prop-types';
  10. class MyComponent extends React.Component {
  11. render() {
  12. // ... do things with the props
  13. }
  14. }
  15. MyComponent.propTypes = {
  16. // You can declare that a prop is a specific JS primitive. By default, these
  17. // are all optional.
  18. optionalArray: PropTypes.array,
  19. optionalBool: PropTypes.bool,
  20. optionalFunc: PropTypes.func,
  21. optionalNumber: PropTypes.number,
  22. optionalObject: PropTypes.object,
  23. optionalString: PropTypes.string,
  24. optionalSymbol: PropTypes.symbol,
  25. // Anything that can be rendered: numbers, strings, elements or an array
  26. // (or fragment) containing these types.
  27. optionalNode: PropTypes.node,
  28. // A React element.
  29. optionalElement: PropTypes.element,
  30. // You can also declare that a prop is an instance of a class. This uses
  31. // JS's instanceof operator.
  32. optionalMessage: PropTypes.instanceOf(Message),
  33. // You can ensure that your prop is limited to specific values by treating
  34. // it as an enum.
  35. optionalEnum: PropTypes.oneOf(['News', 'Photos']),
  36. // An object that could be one of many types
  37. optionalUnion: PropTypes.oneOfType([
  38. PropTypes.string,
  39. PropTypes.number,
  40. PropTypes.instanceOf(Message)
  41. ]),
  42. // An array of a certain type
  43. optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
  44. // An object with property values of a certain type
  45. optionalObjectOf: PropTypes.objectOf(PropTypes.number),
  46. // You can chain any of the above with `isRequired` to make sure a warning
  47. // is shown if the prop isn't provided.
  48. // An object taking on a particular shape
  49. optionalObjectWithShape: PropTypes.shape({
  50. optionalProperty: PropTypes.string,
  51. requiredProperty: PropTypes.number.isRequired
  52. }),
  53. // An object with warnings on extra properties
  54. optionalObjectWithStrictShape: PropTypes.exact({
  55. optionalProperty: PropTypes.string,
  56. requiredProperty: PropTypes.number.isRequired
  57. }),
  58. requiredFunc: PropTypes.func.isRequired,
  59. // A value of any data type
  60. requiredAny: PropTypes.any.isRequired,
  61. // You can also specify a custom validator. It should return an Error
  62. // object if the validation fails. Don't `console.warn` or throw, as this
  63. // won't work inside `oneOfType`.
  64. customProp: function(props, propName, componentName) {
  65. if (!/matchme/.test(props[propName])) {
  66. return new Error(
  67. 'Invalid prop `' + propName + '` supplied to' +
  68. ' `' + componentName + '`. Validation failed.'
  69. );
  70. }
  71. },
  72. // You can also supply a custom validator to `arrayOf` and `objectOf`.
  73. // It should return an Error object if the validation fails. The validator
  74. // will be called for each key in the array or object. The first two
  75. // arguments of the validator are the array or object itself, and the
  76. // current item's key.
  77. customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
  78. if (!/matchme/.test(propValue[key])) {
  79. return new Error(
  80. 'Invalid prop `' + propFullName + '` supplied to' +
  81. ' `' + componentName + '`. Validation failed.'
  82. );
  83. }
  84. })
  85. };

Refer to the React documentation for more information.

Migrating from React.PropTypes

Check out Migrating from React.PropTypes for details on how to migrate to prop-types from React.PropTypes.

Note that this blog posts mentions a codemod script that performs the conversion automatically.

There are also important notes below.

How to Depend on This Package?

For apps, we recommend putting it in dependencies with a caret range. For example:

  1. "dependencies": {
  2. "prop-types": "^15.5.7"
  3. }

For libraries, we also recommend leaving it in dependencies:

  1. "dependencies": {
  2. "prop-types": "^15.5.7"
  3. },
  4. "peerDependencies": {
  5. "react": "^15.5.0"
  6. }

Note: there are known issues in versions before 15.5.7 so we recommend using it as the minimal version.

Make sure that the version range uses a caret (^) and thus is broad enough for npm to efficiently deduplicate packages.

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.

Compatibility

React 0.14

This 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.

  1. # ATTENTION: Only run this if you still use React 0.14!
  2. npm install --save react@^0.14.9 react-dom@^0.14.9

React 15+

This package is compatible with React 15.3.0 and higher.

  1. npm install --save react@^15.3.0 react-dom@^15.3.0

What happens on other React versions?

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.

Difference from React.PropTypes: Don’t Call Validator Functions

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 for more details.

Are you using either React 0.14.9 or a version higher than React 15.3.0? Read on.

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.

Code like this is still fine:

  1. MyComponent.propTypes = {
  2. myProp: PropTypes.bool
  3. };

However, code like this will not work with the prop-types package:

  1. // Will not work with `prop-types` package!
  2. var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop');

It will throw an error:

  1. Calling PropTypes validators directly is not supported by the `prop-types` package.
  2. Use PropTypes.checkPropTypes() to call them.

(If you see a warning rather than an error with this message, please check the above section about compatibility.)

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 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.

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:

  1. // Works with standalone PropTypes
  2. PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent');

See below for more info.

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. Alternatively, you can temporarily keep using React.PropTypes until React 16, as it would still only warn in this case.

If you use a bundler like Browserify or Webpack, don’t forget to follow these instructions to correctly bundle your application in development or production mode. Otherwise you’ll ship unnecessary code to your users.

PropTypes.checkPropTypes

React will automatically check the propTypes you set on the component, but if you are using PropTypes without React then you may want to manually call PropTypes.checkPropTypes, like so:

  1. const myPropTypes = {
  2. name: PropTypes.string,
  3. age: PropTypes.number,
  4. // ... define your prop validations
  5. };
  6. const props = {
  7. name: 'hello', // is valid
  8. age: 'world', // not valid
  9. };
  10. // Let's say your component is called 'MyComponent'
  11. // Works with standalone PropTypes
  12. PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
  13. // This will warn as follows:
  14. // Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
  15. // `MyComponent`, expected `number`.