• Stars
    star
    671
  • Rank 67,266 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated 4 months ago

Reviews

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

Repository Details

Custom React PropType validators

prop-types Version Badge

Build Status dependency status dev dependency status License Downloads

npm badge

Custom React PropType validators that we use at Airbnb. Use of airbnb-js-shims or the equivalent is recommended.

  • and: ensure that all provided propType validators pass
    • foo: and([number, nonNegativeInteger])
  • between: provide an object with an gt or gte number, and an lt or lte number (only one item allowed from each pairs; one or both pairs may be provided), and the resulting propType validator will ensure the prop value is a number within the given range. Alternatively, you can provide a function that takes the props object and returns a number for each of the gt/gte/lt/lte values.
    • foo: between({ gte: 0, lte: 5 })
    • foo: between({ gt: 0, lt: 5 })
  • booleanSome: provide a list of props, and all must be booleans, and at least one of them must be true.
    • foo: booleanSome('small', 'medium', 'large')
  • childrenHavePropXorChildren: ensure that either all children have the indicated prop, all children have children, or all children have neither.
    • foo: childrenHavePropXorChildren('bar')
  • childrenOf: restrict the children prop to only allow children that pass the given propType validator.
    • children: childrenOf(number.isRequired)
  • childrenOfType: restrict the children prop to only allow children of the given element types - takes a Component, an HTML tag name, or "*" to match everything.
    • children: childrenOfType('span')
    • children: childrenOfType(Component)
  • childrenSequenceOf: restrict the children prop to be a sequenceOf the given "specifiers" (see sequenceOf)
    • children: childrenSequenceOf({validator: string, min: 0, max: 5})
  • componentWithName: restrict the prop to only allow a component with a certain name/displayName. Accepts a string, or a regular expression. Also accepts an options object with an optional stripHOCs array of string HOC names to strip off before validating; an HOC name must not contain parentheses and must be in camelCase.
    • foo: componentWithName('Component')
    • foo: componentWithName('Component', { stripHOCs: ['withDirection', 'withStyles'] })
  • disallowedIf: restrict the prop from being provided if the given other prop name matches the given other prop type. The other prop type validator only applies if the other prop name is not a null value.
    • foo: disallowedIf(string, 'bar', bool)
  • elementType: require that the prop be a specific type of React element - takes a Component, an HTML tag name, or "*" to match everything.
    • foo: elementType('span')
    • foo: elementType(Component)
  • empty: a value that React renders to nothing: undefined, null, false, the empty string, or an array of those things.
    • foo: empty()
  • explicitNull: only allow null or undefined/omission - and only null when required.
    • foo: explicitNull()
  • forbidExtraProps: pass your entire propTypes object into this function, and any nonspecified prop will error.
    • Component.propTypes = forbidExtraProps({foo: number.isRequired})
  • integer: require the prop be an integer.
    • foo: integer()
  • keysOf: pass in a proptype, and require all the keys of a prop to have that type
    • foo: keysOf(number)
  • mutuallyExclusiveProps: provide a propType, and a list of props, and only one prop out of the list will be permitted, validated by the given propType.
    • foo: mutuallyExclusiveProps(bool, 'bar', 'sna')
  • mutuallyExclusiveTrueProps: provide a list of props, and all must be booleans, and only one is allowed to be true.
    • foo: mutuallyExclusiveTrueProps('bar', 'sna')
  • nChildren: require a specific amount of children.
    • children: nChildren(3)
    • children: nChildren(3, childrenOfType('span'))
  • nonNegativeInteger: require that the prop be a number, that is 0, or a finite positive integer.
    • foo: nonNegativeInteger()
  • nonNegativeNumber: require that the prop be a number, that is 0, or a finite positive number.
    • foo: nonNegativeNumber()
  • numericString: require the prop be a string that is conceptually numeric.
    • foo: numericString()
  • object: same as PropTypes.object, but can be called outside of React's propType flow.
  • or: recursively allows only the provided propTypes, or arrays of those propTypes.
    • foo: or([bool.isRequired, explicitNull()])
  • predicate: provide a predicate function, and an optional message, and will fail when the predicate returns false.
    • foo: predicate((x) => x % 2 === 0, 'must be an even integer')
  • range: provide a min, and a max, and the prop must be an integer in the range [min, max)
    • foo: range(-1, 2)
  • ref: require the prop to be a React ref. These can be either the object returned from React.createRef() or "callback" refs.
    • foo: ref()
  • requiredBy: pass in a prop name and propType, and require that the prop is defined and is not its default value if the passed in prop name is truthy. if the default value is not provided, defaults to checking against null.
    • foo: requiredBy('bar', bool)
  • restrictedProp: this prop is not permitted to be anything but null or undefined.
    • foo: restrictedProp()
    • foo: restrictedProp(new TypeError('Custom Error'))
  • sequenceOf: takes 1 or more "specifiers": an object with a "validator" function (a propType validator), a "min" nonNegativeInteger, and a "max" nonNegativeInteger. If both "min" and "max" may be omitted, they default to 1; if only "max" is omitted, it defaults to Infinity; if only "min" is omitted, it defaults to 1.
    • foo: sequenceOf({validator: string, min: 0, max: 5})
  • shape: takes a shape, and allows it to be enforced on any non-null/undefined value.
    • foo: shape({ length: oneOf([2]) })
  • stringEndsWith: takes a non-empty string, and returns a validator that ensures the prop value is a string that ends with it.
    • foo: stringEndsWith('.png')
  • stringStartsWith: takes a non-empty string, and returns a validator that ensures the prop value is a string that starts with it.
    • foo: stringStartsWith('prefix-')
  • uniqueArray: this prop must be an array, and all values must be unique (determined by Object.is). Like PropTypes.array, but with uniqueness.
    • foo: uniqueArray()
  • uniqueArrayOf: uniqueArray, with a type validator applied. Like PropTypes.arrayOf, but with uniqueness. Can also take an optional mapper function that allows for a non-standard unique calculation (otherwise, Object.is is used by default). The function is applied to each element in the array, and the resulting values are compared using the standard unique calculation.
    • foo: uniqueArrayOf(number)
    • foo: uniqueArrayOf(element => element ** 2)
    • foo: uniqueArrayOf(element => element ** 2, 'test')
    • foo: uniqueArrayOf(array, element => element[0] ** 2, 'test')
  • valuesOf: a non-object requiring PropTypes.objectOf. Takes a propType validator, and applies it to every own value on the propValue.
    • foo: valuesOf(number)
  • withShape: takes a PropType and a shape, and allows it to be enforced on any non-null/undefined value.
    • foo: withShape(array, { length: oneOf([2]) })

Production

Since PropTypes are typically not included in production builds of React, this library’s functionality serves no useful purpose. As such, when the NODE_ENV environment variable is "production", instead of exporting the implementations of all these prop types, we export mock functions - in other words, something that ensures that no exceptions are thrown, but does no validation. When environment variables are inlined (via a browserify transform or webpack plugin), then tools like webpack or uglify are able to determine that only the mocks will be imported - and can avoid including the entire implementations in the final bundle that is sent to the browser. This allows for a much smaller ultimate file size, and faster in-browser performance, without sacrificing the benefits of PropTypes themselves.

Tests

Clone the repo, npm install, npm run react, and run npm test

More Repositories

1

qs

A querystring parser with nesting support
JavaScript
8,010
star
2

tape

tap-producing test harness for node and browsers
JavaScript
5,740
star
3

faucet

human-readable TAP summarizer
JavaScript
547
star
4

testling

unit tests in all the browsers
JavaScript
353
star
5

prop-types-exact

For use with React PropTypes. Will error on any prop not explicitly specified.
JavaScript
236
star
6

util.promisify

Polyfill/shim for util.promisify in node versions < v8
JavaScript
120
star
7

object.assign

ES6 spec-compliant Object.assign shim. From https://github.com/es-shims/es6-shim
JavaScript
105
star
8

es-abstract

ECMAScript spec abstract operations.
JavaScript
98
star
9

json-stable-stringify

JavaScript
55
star
10

ls-engines

Determine if your dependency graph's stated "engines" criteria is met.
JavaScript
49
star
11

js-traverse

JavaScript
46
star
12

json-file-plus

Read from and write to a JSON file, minimizing diffs and preserving formatting.
JavaScript
43
star
13

object-keys

Object.keys shim
JavaScript
43
star
14

istanbul-merge

Merge multiple istanbul coverage reports into one.
JavaScript
42
star
15

npmignore

Command line tool for creating or updating a .npmignore file based on .gitignore.
JavaScript
27
star
16

aud

Use `npx aud` instead of `npm audit`, whether you have a lockfile or not!
JavaScript
26
star
17

shell-quote

JavaScript
26
star
18

get-intrinsic

Get and robustly cache all JS language-level intrinsics at first require time.
JavaScript
25
star
19

listify

Turn an array into a list of comma-separated values, appropriate for use in an English sentence.
JavaScript
25
star
20

simd

ES7 (proposed) SIMD numeric type shim/polyfill
JavaScript
24
star
21

repo-report

CLI to list all repos a user has access to, and report on their configuration in aggregate.
JavaScript
24
star
22

publishers

Provide a package name, get a list of every version, and who published it.
JavaScript
24
star
23

es-to-primitive

ECMAScript "ToPrimitive" algorithm. Provides ES5 and ES6/ES2015 versions.
JavaScript
22
star
24

safe-publish-latest

Ensure that when you `npm publish`, the "latest" tag is only set for the truly latest version.
JavaScript
21
star
25

define-properties

Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines.
JavaScript
20
star
26

global-cache

Sometimes you have to do horrible things, like use the global object to share a singleton. Abstract that away, with this!
JavaScript
20
star
27

promise-deferred

A lightweight Deferred implementation, on top of Promises/A+
JavaScript
19
star
28

eslint-config

My shareable `eslint` config.
JavaScript
19
star
29

ljharb

19
star
30

camelize

JavaScript
16
star
31

require-allow-edits

A GitHub action to require "allow edits" to be checked on a PR.
JavaScript
16
star
32

can-merge

JavaScript
15
star
33

get-dep-tree

Use npm's Arborist to get a dependency tree for a package.
JavaScript
14
star
34

side-channel

Store information about any JS value in a side channel. Uses WeakMap if available.
JavaScript
14
star
35

es-get-iterator

Get an iterator for any JS language value. Works robustly across all environments, all versions.
JavaScript
13
star
36

list-exports

Given a package name and a version number, or a path to a package.json, what specifiers does it expose?
JavaScript
13
star
37

get-nans

Get an array of all distinct NaN values supported by the engine. There can be only one!
JavaScript
12
star
38

tsconfig

My personal tsconfig(s), so my open source projects can share them.
12
star
39

actions

GitHub actions I use for CI.
JavaScript
11
star
40

uglify-register

The require hook will bind itself to node's require and automatically uglify files on the fly.
JavaScript
11
star
41

promiseback

Accept an optional node-style callback, and also return a spec-compliant Promise!
JavaScript
10
star
42

html-element-map

Look up HTML tag names via HTML Element constructors, and vice versa.
JavaScript
10
star
43

es-errors

A simple cache for a few of the JS Error constructors.
JavaScript
10
star
44

call-bind

Robustly `.call.bind()` a function.
JavaScript
9
star
45

scorecard-cli

A CLI for OpenSSF Scorecard data.
JavaScript
9
star
46

ls-publishers

List your dependency graph, grouped by publishers.
JavaScript
8
star
47

proposal-is-error

ECMAScript Proposal, specs, and reference implementation for Error.isError
CSS
8
star
48

safe-regex-test

Give a regex, get a robust predicate function that tests it against a string.
JavaScript
8
star
49

unused-files

List unused files in your package.
JavaScript
8
star
50

mock-property

Given an object and a property, replaces a property descriptor (or deletes it), and returns a thunk to restore it.
JavaScript
8
star
51

private-fields

What private fields does this object have?
JavaScript
6
star
52

set-function-length

Set a function's length property
JavaScript
6
star
53

unbox-primitive

Unbox a boxed JS primitive value.
JavaScript
6
star
54

document.contains

Polyfill/shim for `document.contains`
JavaScript
5
star
55

npm-lockfile

Safely generate an npm lockfile and output it to the filename of your choice.
JavaScript
5
star
56

make-generator-function

Returns an arbitrary generator function, or undefined if generator syntax is unsupported.
JavaScript
5
star
57

internal-slot

ES spec-like internal slots.
JavaScript
5
star
58

safe-array-concat

`Array.prototype.concat`, but made safe by ignoring Symbol.isConcatSpreadable
JavaScript
5
star
59

npm-deprecations

Given an npm module name, get a map of npm version numbers to deprecation messages.
JavaScript
5
star
60

find-value-locations

Given an object, and a value, return a tuple of the property name, and the object on which it is an own property.
JavaScript
5
star
61

set-function-name

Set a function's name property
JavaScript
4
star
62

stop-iteration-iterator

Firefox 17-26 iterators throw a StopIteration object to indicate "done". This normalizes it.
JavaScript
4
star
63

intl-fallback-symbol

ECMA-402 Intl spec's internal `FallbackSymbol`
JavaScript
4
star
64

make-async-function

Function that returns an arbitrary `async function`, or undefined if `async function` syntax is unsupported.
JavaScript
4
star
65

define-data-property

Define a data property on an object. Will fall back to assignment in an engine without descriptors.
JavaScript
4
star
66

jsonify

JavaScript
4
star
67

.github

4
star
68

tc39-ci

Begin app
JavaScript
4
star
69

es-define-property

`Object.defineProperty`, but not IE 8's broken one.
JavaScript
4
star
70

iterate-value

Iterate any iterable JS value. Works robustly in all environments, all versions.
JavaScript
3
star
71

daytime

npm module to combine two Date objects, "day" and "time"
JavaScript
3
star
72

iterate-iterator

Iterate any JS iterator. Works robustly in all environments, all versions.
JavaScript
3
star
73

concat-map

JavaScript
3
star
74

es-value-fixtures

Fixtures of ES values, for testing purposes.
JavaScript
3
star
75

big-integer-max

Given two valid integers in string form, return the larger of the two.
JavaScript
3
star
76

node-comments

Transform comments in JS files between multiple styles - single-line, multi-line, both, and more to come!
JavaScript
3
star
77

make-arrow-function

Function that returns an arbitrary arrow function, or undefined if arrow function syntax is unsupported.
JavaScript
3
star
78

define-accessor-property

Define an accessor property on an object. Will either throw, or fall back to assignment in loose mode, in an engine without descriptors.
JavaScript
3
star
79

es-object-atoms

ES Object-related atoms: Object, ToObject, RequireObjectCoercible
JavaScript
3
star
80

gfm-footnotes

Prune unused footnote references in GitHub-flavored Markdown
JavaScript
2
star
81

renovate

Shared renovate config.
2
star
82

big-integer-min

Given two valid integers in string form, return the smaller of the two.
JavaScript
2
star
83

lockfile-info

Info about an npm project - which lockfile version, which lockfile(s) are present, etc.
JavaScript
2
star
84

gopd

`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.
JavaScript
2
star
85

resumer

a through stream that starts paused and resumes on the next tick
JavaScript
2
star
86

AsyncIterator.prototype

`AsyncIterator.prototype`, or a shared object to use.
JavaScript
2
star
87

TcoExpand

Expands t.co short links on twitter.com when possible. This only works because Twitter provides the full URL as a data attribute on most shortened links - it's quick and dirty, it may break at any time, and it depends on jQuery to work.
JavaScript
2
star
88

es-shim-unscopables

Helper package to shim a method into `Array.prototype[Symbol.unscopables]`
JavaScript
2
star
89

primordials

node core's "primordials" module, but robust for use in a published package
2
star
90

safe-bigint

Safely create a BigInt from a numerical string, even one larger than MAX_SAFE_INTEGER.
JavaScript
2
star
91

coauthors

A cli to generate a complete git co-authors list, including existing co-authors, for use in a commit message.
JavaScript
2
star
92

open-sauced-goals

1
star
93

es-array-method-boxes-properly

Utility package to determine if an `Array.prototype` method properly boxes the callback's receiver and third argument.
JavaScript
1
star
94

Iterator.prototype

`Iterator.prototype`, or a shared object to use.
JavaScript
1
star
95

array-map

JavaScript
1
star
96

keytween

Encode and decode a string using the "look between X and Y on your keyboard" meme format
JavaScript
1
star
97

repo-report-cache

JavaScript
1
star
98

make-async-generator-function

Function that returns an arbitrary async generator function, or undefined if async generator syntax is unsupported.
JavaScript
1
star
99

validate-exports-object

Validate an object in the "exports" field.
JavaScript
1
star
100

possible-typed-array-names

A simple list of possible Typed Array names.
JavaScript
1
star