Runtime type checking for React props and similar objects
Installations
npm install prop-types
Score
94.2
Supply Chain
100
Quality
79.5
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
17.3.0
NPM Version
8.3.0
Statistics
4,482 Stars
171 Commits
358 Forks
53 Watching
5 Branches
114 Contributors
Updated on 25 Nov 2024
Bundle Size
906.00 B
Minified
536.00 B
Minified + Gzipped
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
4,724,131,533
Last day
-3.6%
5,245,097
Compared to previous day
Last week
3%
28,238,763
Compared to previous week
Last month
12.8%
116,222,050
Compared to previous month
Last year
10.1%
1,233,452,141
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
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
1npm install --save prop-types
Importing
1import PropTypes from 'prop-types'; // ES6 2var 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:
1<!-- development version --> 2<script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script> 3 4<!-- production version --> 5<script src="https://unpkg.com/prop-types@15.6/prop-types.min.js"></script>
1<!-- development version --> 2<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script> 3 4<!-- production version --> 5<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
To load a specific version of prop-types
replace 15.6.0
with the version number.
Usage
PropTypes was originally exposed as part of the React core module, and is commonly used with React components. Here is an example of using PropTypes with a React component, which also documents the different validators provided:
1import React from 'react';
2import PropTypes from 'prop-types';
3
4class MyComponent extends React.Component {
5 render() {
6 // ... do things with the props
7 }
8}
9
10MyComponent.propTypes = {
11 // You can declare that a prop is a specific JS primitive. By default, these
12 // are all optional.
13 optionalArray: PropTypes.array,
14 optionalBigInt: PropTypes.bigint,
15 optionalBool: PropTypes.bool,
16 optionalFunc: PropTypes.func,
17 optionalNumber: PropTypes.number,
18 optionalObject: PropTypes.object,
19 optionalString: PropTypes.string,
20 optionalSymbol: PropTypes.symbol,
21
22 // Anything that can be rendered: numbers, strings, elements or an array
23 // (or fragment) containing these types.
24 // see https://reactjs.org/docs/rendering-elements.html for more info
25 optionalNode: PropTypes.node,
26
27 // A React element (ie. <MyComponent />).
28 optionalElement: PropTypes.element,
29
30 // A React element type (eg. MyComponent).
31 // a function, string, or "element-like" object (eg. React.Fragment, Suspense, etc.)
32 // see https://github.com/facebook/react/blob/HEAD/packages/shared/isValidElementType.js
33 optionalElementType: PropTypes.elementType,
34
35 // You can also declare that a prop is an instance of a class. This uses
36 // JS's instanceof operator.
37 optionalMessage: PropTypes.instanceOf(Message),
38
39 // You can ensure that your prop is limited to specific values by treating
40 // it as an enum.
41 optionalEnum: PropTypes.oneOf(['News', 'Photos']),
42
43 // An object that could be one of many types
44 optionalUnion: PropTypes.oneOfType([
45 PropTypes.string,
46 PropTypes.number,
47 PropTypes.instanceOf(Message)
48 ]),
49
50 // An array of a certain type
51 optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
52
53 // An object with property values of a certain type
54 optionalObjectOf: PropTypes.objectOf(PropTypes.number),
55
56 // You can chain any of the above with `isRequired` to make sure a warning
57 // is shown if the prop isn't provided.
58
59 // An object taking on a particular shape
60 optionalObjectWithShape: PropTypes.shape({
61 optionalProperty: PropTypes.string,
62 requiredProperty: PropTypes.number.isRequired
63 }),
64
65 // An object with warnings on extra properties
66 optionalObjectWithStrictShape: PropTypes.exact({
67 optionalProperty: PropTypes.string,
68 requiredProperty: PropTypes.number.isRequired
69 }),
70
71 requiredFunc: PropTypes.func.isRequired,
72
73 // A value of any data type
74 requiredAny: PropTypes.any.isRequired,
75
76 // You can also specify a custom validator. It should return an Error
77 // object if the validation fails. Don't `console.warn` or throw, as this
78 // won't work inside `oneOfType`.
79 customProp: function(props, propName, componentName) {
80 if (!/matchme/.test(props[propName])) {
81 return new Error(
82 'Invalid prop `' + propName + '` supplied to' +
83 ' `' + componentName + '`. Validation failed.'
84 );
85 }
86 },
87
88 // You can also supply a custom validator to `arrayOf` and `objectOf`.
89 // It should return an Error object if the validation fails. The validator
90 // will be called for each key in the array or object. The first two
91 // arguments of the validator are the array or object itself, and the
92 // current item's key.
93 customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
94 if (!/matchme/.test(propValue[key])) {
95 return new Error(
96 'Invalid prop `' + propFullName + '` supplied to' +
97 ' `' + componentName + '`. Validation failed.'
98 );
99 }
100 })
101};
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 in March of 2016), 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! 2npm install --save react@^0.14.9 react-dom@^0.14.9
React 15+
This package is compatible with React 15.3.0 and higher.
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:
1MyComponent.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! 2var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop');
It will throw an error:
Calling PropTypes validators directly is not supported by the `prop-types` package.
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
2PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent');
See below for more info.
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
.
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:
1const myPropTypes = {
2 name: PropTypes.string,
3 age: PropTypes.number,
4 // ... define your prop validations
5};
6
7const props = {
8 name: 'hello', // is valid
9 age: 'world', // not valid
10};
11
12// Let's say your component is called 'MyComponent'
13
14// Works with standalone PropTypes
15PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
16// This will warn as follows:
17// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
18// `MyComponent`, expected `number`.
PropTypes.resetWarningCache()
PropTypes.checkPropTypes(...)
only console.error
s a given message once. To reset the error warning cache in tests, call PropTypes.resetWarningCache()
License
prop-types is MIT licensed.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
- Info: topLevel 'contents' permission set to 'read': .github/workflows/ci.yml:7
- Info: no jobLevel write permissions found
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/facebook/.github/SECURITY.md:1
- Info: Found linked content: github.com/facebook/.github/SECURITY.md:1
- Warn: One or no descriptive hints of disclosure, vulnerability, and/or timelines in security policy
- Info: Found text in security policy: github.com/facebook/.github/SECURITY.md:1
Reason
Found 11/20 approved changesets -- score normalized to 5
Reason
project is archived
Details
- Warn: Repository is archived.
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/facebook/prop-types/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/facebook/prop-types/ci.yml/main?enable=pin
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 24 are checked with a SAST tool
Reason
21 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-cwfw-4gq5-mrqx
- Warn: Project is vulnerable to: GHSA-g95f-p29q-9xw4
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-x9w5-v3q2-3rhw
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-434g-2637-qmqr
- Warn: Project is vulnerable to: GHSA-49q7-c7j4-3p7m
- Warn: Project is vulnerable to: GHSA-977x-g7h5-7qgw
- Warn: Project is vulnerable to: GHSA-f7q4-pwc6-w24p
- Warn: Project is vulnerable to: GHSA-fc9h-whq2-v747
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-7wpw-2hjm-89gp
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-r683-j2x4-v87g
- Warn: Project is vulnerable to: GHSA-5fw9-fq32-wv5p
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-4wf5-vphf-c2xc
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp
Score
4.9
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More