• Stars
    star
    4,427
  • Rank 9,195 (Top 0.2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Runtime type checking for React props and similar objects

prop-types Support Ukraine Build Status

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

npm install --save prop-types

Importing

import PropTypes from 'prop-types'; // ES6
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:

<!-- development version -->
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>

<!-- production version -->
<script src="https://unpkg.com/[email protected]/prop-types.min.js"></script>
<!-- development version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>

<!-- production version -->
<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:

import React from 'react';
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  render() {
    // ... do things with the props
  }
}

MyComponent.propTypes = {
  // You can declare that a prop is a specific JS primitive. By default, these
  // are all optional.
  optionalArray: PropTypes.array,
  optionalBigInt: PropTypes.bigint,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // Anything that can be rendered: numbers, strings, elements or an array
  // (or fragment) containing these types.
  // see https://reactjs.org/docs/rendering-elements.html for more info
  optionalNode: PropTypes.node,

  // A React element (ie. <MyComponent />).
  optionalElement: PropTypes.element,

  // A React element type (eg. MyComponent).
  // a function, string, or "element-like" object (eg. React.Fragment, Suspense, etc.)
  // see https://github.com/facebook/react/blob/HEAD/packages/shared/isValidElementType.js
  optionalElementType: PropTypes.elementType,

  // You can also declare that a prop is an instance of a class. This uses
  // JS's instanceof operator.
  optionalMessage: PropTypes.instanceOf(Message),

  // You can ensure that your prop is limited to specific values by treating
  // it as an enum.
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // An object that could be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // An array of a certain type
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // An object with property values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // You can chain any of the above with `isRequired` to make sure a warning
  // is shown if the prop isn't provided.

  // An object taking on a particular shape
  optionalObjectWithShape: PropTypes.shape({
    optionalProperty: PropTypes.string,
    requiredProperty: PropTypes.number.isRequired
  }),

  // An object with warnings on extra properties
  optionalObjectWithStrictShape: PropTypes.exact({
    optionalProperty: PropTypes.string,
    requiredProperty: PropTypes.number.isRequired
  }),

  requiredFunc: PropTypes.func.isRequired,

  // A value of any data type
  requiredAny: PropTypes.any.isRequired,

  // You can also specify a custom validator. It should return an Error
  // object if the validation fails. Don't `console.warn` or throw, as this
  // won't work inside `oneOfType`.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // You can also supply a custom validator to `arrayOf` and `objectOf`.
  // It should return an Error object if the validation fails. The validator
  // will be called for each key in the array or object. The first two
  // arguments of the validator are the array or object itself, and the
  // current item's key.
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
};

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:

  "dependencies": {
    "prop-types": "^15.5.7"
  }

For libraries, we also recommend leaving it in dependencies:

  "dependencies": {
    "prop-types": "^15.5.7"
  },
  "peerDependencies": {
    "react": "^15.5.0"
  }

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.

# ATTENTION: Only run this if you still use React 0.14!
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.

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:

MyComponent.propTypes = {
  myProp: PropTypes.bool
};

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

// Will not work with `prop-types` package!
var 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:

// Works with standalone PropTypes
PropTypes.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:

const myPropTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  // ... define your prop validations
};

const props = {
  name: 'hello', // is valid
  age: 'world', // not valid
};

// Let's say your component is called 'MyComponent'

// Works with standalone PropTypes
PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
// This will warn as follows:
// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
// `MyComponent`, expected `number`.

PropTypes.resetWarningCache()

PropTypes.checkPropTypes(...) only console.errors a given message once. To reset the error warning cache in tests, call PropTypes.resetWarningCache()

License

prop-types is MIT licensed.

More Repositories

1

react

The library for web and native user interfaces.
JavaScript
221,340
star
2

react-native

A framework for building native applications using React
C++
115,446
star
3

create-react-app

Set up a modern web app by running one command.
JavaScript
101,534
star
4

docusaurus

Easy to maintain open source documentation websites.
TypeScript
52,724
star
5

jest

Delightful JavaScript Testing.
TypeScript
41,554
star
6

rocksdb

A library that provides an embeddable, persistent key-value store for fast storage.
C++
27,271
star
7

folly

An open-source C++ library developed and used at Facebook.
C++
26,731
star
8

flow

Adds static typing to JavaScript to improve developer productivity and code quality.
OCaml
22,040
star
9

zstd

Zstandard - Fast real-time compression algorithm
C
21,685
star
10

relay

Relay is a JavaScript framework for building data-driven React applications.
Rust
18,099
star
11

hhvm

A virtual machine for executing programs written in Hack.
C++
17,960
star
12

prophet

Tool for producing high quality forecasts for time series data that has multiple seasonality with linear or non-linear growth.
Python
17,624
star
13

fresco

An Android library for managing images and the memory they use.
Java
17,026
star
14

lexical

Lexical is an extensible text editor framework that provides excellent reliability, accessibility and performance.
TypeScript
16,985
star
15

yoga

Yoga is a cross-platform layout engine which implements Flexbox. Follow https://twitter.com/yogalayout for updates.
C++
16,729
star
16

infer

A static analyzer for Java, C, C++, and Objective-C
OCaml
14,599
star
17

flipper

A desktop debugging platform for mobile developers.
TypeScript
13,124
star
18

watchman

Watches files and records, or triggers actions, when they change.
C++
12,124
star
19

react-devtools

An extension that allows inspection of React component hierarchy in the Chrome and Firefox Developer Tools.
11,024
star
20

hermes

A JavaScript engine optimized for running React Native.
C++
9,167
star
21

chisel

Chisel is a collection of LLDB commands to assist debugging iOS apps.
Python
9,072
star
22

jscodeshift

A JavaScript codemod toolkit.
JavaScript
8,850
star
23

buck

A fast build system that encourages the creation of small, reusable modules over a variety of platforms and languages.
Java
8,568
star
24

stylex

StyleX is the styling system for ambitious user interfaces.
JavaScript
7,988
star
25

proxygen

A collection of C++ HTTP libraries including an easy to use HTTP server.
C++
7,978
star
26

facebook-ios-sdk

Used to integrate the Facebook Platform with your iOS & tvOS apps.
Swift
7,644
star
27

litho

A declarative framework for building efficient UIs on Android.
Java
7,633
star
28

pyre-check

Performant type-checking for python.
OCaml
6,620
star
29

facebook-android-sdk

Used to integrate Android apps with Facebook Platform.
Kotlin
6,020
star
30

redex

A bytecode optimizer for Android apps
C++
5,951
star
31

componentkit

A React-inspired view framework for iOS.
Objective-C++
5,740
star
32

sapling

A Scalable, User-Friendly Source Control System.
Rust
5,635
star
33

fishhook

A library that enables dynamically rebinding symbols in Mach-O binaries running on iOS.
C
5,061
star
34

PathPicker

PathPicker accepts a wide range of input -- output from git commands, grep results, searches -- pretty much anything. After parsing the input, PathPicker presents you with a nice UI to select which files you're interested in. After that you can open them in your favorite editor or execute arbitrary commands.
Python
5,033
star
35

metro

🚇 The JavaScript bundler for React Native
JavaScript
4,996
star
36

idb

idb is a flexible command line interface for automating iOS simulators and devices
Objective-C
4,356
star
37

Haxl

A Haskell library that simplifies access to remote data, such as databases or web-based services.
Haskell
4,220
star
38

FBRetainCycleDetector

iOS library to help detecting retain cycles in runtime.
Objective-C++
4,178
star
39

memlab

A framework for finding JavaScript memory leaks and analyzing heap snapshots
TypeScript
4,088
star
40

duckling

Language, engine, and tooling for expressing, testing, and evaluating composable language rules on input strings.
Haskell
3,995
star
41

fbt

A JavaScript Internationalization Framework
JavaScript
3,836
star
42

regenerator

Source transformer enabling ECMAScript 6 generator functions in JavaScript-of-today.
JavaScript
3,795
star
43

mcrouter

Mcrouter is a memcached protocol router for scaling memcached deployments.
C++
3,186
star
44

buck2

Build system, successor to Buck
Rust
3,177
star
45

wangle

Wangle is a framework providing a set of common client/server abstractions for building services in a consistent, modular, and composable way.
C++
3,016
star
46

wdt

Warp speed Data Transfer (WDT) is an embeddedable library (and command line tool) aiming to transfer data between 2 systems as fast as possible over multiple TCP paths.
C++
2,827
star
47

igl

Intermediate Graphics Library (IGL) is a cross-platform library that commands the GPU. It provides a single low-level cross-platform interface on top of various graphics APIs (e.g. OpenGL, Metal and Vulkan).
C++
2,674
star
48

fbthrift

Facebook's branch of Apache Thrift, including a new C++ server.
C++
2,513
star
49

mysql-5.6

Facebook's branch of the Oracle MySQL database. This includes MyRocks.
C++
2,423
star
50

Ax

Adaptive Experimentation Platform
Python
2,226
star
51

jsx

The JSX specification is a XML-like syntax extension to ECMAScript.
HTML
1,941
star
52

fbjs

A collection of utility libraries used by other Meta JS projects.
JavaScript
1,939
star
53

react-native-website

The React Native website and docs
JavaScript
1,875
star
54

screenshot-tests-for-android

Generate fast deterministic screenshots during Android instrumentation tests
Java
1,727
star
55

idx

Library for accessing arbitrarily nested, possibly nullable properties on a JavaScript object.
JavaScript
1,687
star
56

TextLayoutBuilder

An Android library that allows you to build text layouts more easily.
Java
1,464
star
57

mvfst

An implementation of the QUIC transport protocol.
C++
1,384
star
58

SoLoader

Native code loader for Android
Java
1,269
star
59

facebook-python-business-sdk

Python SDK for Meta Marketing APIs
Python
1,211
star
60

ThreatExchange

Trust & Safety tools for working together to fight digital harms.
C++
1,092
star
61

mariana-trench

A security focused static analysis tool for Android and Java applications.
C++
1,022
star
62

CacheLib

Pluggable in-process caching engine to build and scale high performance services
C++
1,018
star
63

fatal

Fatal is a library for fast prototyping software in modern C++. It provides facilities to enhance the expressive power of C++. The library is heavily based on template meta-programming, while keeping the complexity under-the-hood.
C++
993
star
64

transform360

Transform360 is an equirectangular to cubemap transform for 360 video.
C
991
star
65

openr

Distributed platform for building autonomic network functions.
C++
879
star
66

fboss

Facebook Open Switching System Software for controlling network switches.
C++
842
star
67

facebook-php-business-sdk

PHP SDK for Meta Marketing API
PHP
787
star
68

ktfmt

A program that reformats Kotlin source code to comply with the common community standard for Kotlin code conventions.
Kotlin
776
star
69

winterfell

A STARK prover and verifier for arbitrary computations
Rust
691
star
70

pyre2

Python wrapper for RE2
C++
629
star
71

openbmc

OpenBMC is an open software framework to build a complete Linux image for a Board Management Controller (BMC).
C
607
star
72

SPARTA

SPARTA is a library of software components specially designed for building high-performance static analyzers based on the theory of Abstract Interpretation.
C++
604
star
73

chef-cookbooks

Open source chef cookbooks.
Ruby
561
star
74

IT-CPE

Meta's Client Platform Engineering tools. Some of the tools we have written to help manage our fleet of client systems.
Ruby
553
star
75

time

Meta's Time libraries
Go
471
star
76

facebook-nodejs-business-sdk

Node.js SDK for Meta Marketing APIs
JavaScript
464
star
77

facebook-sdk-for-unity

The facebook sdk for unity.
C#
461
star
78

lexical-ios

Lexical iOS is an extensible text editor framework that integrates the APIs and philosophies from Lexical Web with a Swift API built on top of TextKit.
Swift
446
star
79

Rapid

The OpenStreetMap editor driven by open data, AI, and supercharged features
JavaScript
425
star
80

FAI-PEP

Facebook AI Performance Evaluation Platform
Python
379
star
81

facebook-java-business-sdk

Java SDK for Meta Marketing APIs
Java
374
star
82

chef-utils

Utilities related to Chef
Ruby
287
star
83

opaque-ke

An implementation of the OPAQUE password-authenticated key exchange protocol
Rust
262
star
84

dns

Collection of Meta's DNS Libraries
Go
251
star
85

facebook360_dep

Facebook360 Depth Estimation Pipeline - https://facebook.github.io/facebook360_dep
HTML
238
star
86

akd

An implementation of an auditable key directory
Rust
207
star
87

tac_plus

A Tacacs+ Daemon tested on Linux (CentOS) to run AAA via TACACS+ Protocol via IPv4 and IPv6.
C
205
star
88

facebook-ruby-business-sdk

Ruby SDK for Meta Marketing API
Ruby
200
star
89

dotslash

Simplified executable deployment
Rust
165
star
90

usort

Safe, minimal import sorting for Python projects.
Python
161
star
91

grocery-delivery

The Grocery Delivery utility for managing cookbook uploads to distributed Chef backends.
Ruby
151
star
92

taste-tester

Software to manage a chef-zero instance and use it to test changes on production servers.
Ruby
144
star
93

TestSlide

A Python test framework
Python
139
star
94

homebrew-fb

OS X Homebrew formulas to install Meta open source software
Ruby
122
star
95

sapp

Post Processor for Facebook Static Analysis Tools.
Python
122
star
96

squangle

SQuangLe is a C++ API for accessing MySQL servers
C++
119
star
97

threat-research

Welcome to the Meta Threat Research Indicator Repository, a dedicated resource for the sharing of Indicators of Compromise (IOCs) and other threat indicators with the external research community
Python
115
star
98

ocamlrep

Sets of libraries and tools to write applications and libraries mixing OCaml and Rust. These libraries will help keeping your types and data structures synchronized, and enable seamless exchange between OCaml and Rust
Rust
97
star
99

bpfilter

BPF-based packet filtering framework
C
79
star
100

facebook-business-sdk-codegen

Codegen project for our business SDKs
PHP
74
star