Coder Social home page Coder Social logo

prop-types's Introduction

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 [email protected]^0.14.9 [email protected]^0.14.9

React 15+

This package is compatible with React 15.3.0 and higher.

npm install --save [email protected]^15.3.0 [email protected]^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.

prop-types's People

Contributors

gaearon avatar ljharb avatar acdlite avatar flarnie avatar aweary avatar jaller94 avatar getkey avatar sophiebits avatar dependabot[bot] avatar noscripter avatar KonstHardy avatar mridgway avatar wojtekmaj avatar adambowles avatar oyeanuj avatar autra avatar benwiley4000 avatar eXon avatar bvaughn avatar chentsulin avatar stof avatar conartist6 avatar dmitryvinn avatar dferber90 avatar gbroques avatar mhkasif avatar JasonEtco avatar jaydenseric avatar jimf avatar johann-sonntagbauer avatar

Stargazers

Z Perez avatar Alexandra avatar Javed Baloch avatar Ozgur Cetin avatar Shaikh Awais-al-waissy avatar Thanh LE avatar Ecode avatar Htet Oo Wai Yan avatar Daniel Fuentes Busco avatar Abdul Rehman avatar Ejiro Asiuwhu avatar  avatar Rosário Pereira Fernandes avatar Paulo Phagula avatar Dilruba Başaran avatar  avatar gepiko avatar ZNM avatar David Pella avatar Seir avatar Henry Bui avatar Chris Wong avatar Δli avatar  avatar 蓝时律月 avatar alanaudi avatar Drew Daniels avatar Chris Hunter avatar Vishal Ludhrani avatar Kai avatar Jakub Was avatar kaifang.wang avatar  avatar David Fernando avatar Lucas Litton avatar  avatar F_Piacacho avatar  avatar Henry Kulmala avatar  avatar h avatar Sourav Singh Rawat avatar Borys Hlazman avatar 张梦君 avatar takna avatar Saeed Kefayati avatar  avatar Barad avatar Ramesh Sachan avatar Martin Šimeček avatar Jeordin Callister avatar Ralph Lauren avatar João Pedro avatar Matt Wigham avatar Huiren Woo avatar  avatar Mr.Sea avatar Bruno Silva avatar André Matthies avatar Dody avatar  avatar Рудоманенко Владимир avatar Ali Mammadli avatar Phillip Sturgeon avatar LukasDoesDev avatar  avatar Renán Romero avatar Frank Lemanschik avatar Ekaterina Martynko avatar Rishabh Singh avatar Adel avatar Joowon Jang avatar jerome avatar Kris Stern avatar  avatar Max Breitsprecher avatar Kyle(Tình Vũ) avatar George Kontridze avatar Shady Tollipop avatar Doha Lee avatar 麦谷 avatar Daniel Oliveira avatar maycon silva avatar Caio Agiani avatar Geoff Davis avatar Mardin avatar Arash avatar Joy avatar  avatar Paramate Tawilapakul avatar c2FhbW5ndXllbg== avatar xunfeng avatar  avatar Lucas Guilherme avatar new/bird avatar Martin Pagels avatar  avatar David Hérault avatar  avatar Kayo Ronald avatar

Watchers

Dario Alves Junior avatar Jordan Harband avatar Sebastian Markbåge avatar Ryan Florence avatar Syamsundar Bhimavarapu avatar Cristiano Contin avatar Toru Kobayashi avatar Seth Webster avatar João Olivio Neto avatar James Cloos avatar Arkadiusz Szaleniec avatar daoyuly avatar Augusto Gerardo Sotelo Labarca avatar Flarnie Marchan avatar zhangaz1 avatar Samuel Susla avatar Andrei Arkhipov avatar Alin Porumb avatar Andrew Clark avatar fred avatar Zesky See avatar Dududu avatar Tin Ha avatar Wellington Torrejais da Silva avatar Fred avatar Yasser Kaddour avatar Adam Raposo avatar  avatar Michael O'Hara avatar Luke Chang avatar Maxfocker avatar Mehmet Korkut avatar Zim avatar solrac901 avatar  avatar Kry avatar Reberth da Silva avatar Artem Fedulov avatar  avatar 卷尺 avatar lhsshun avatar ShunqiHuang avatar  avatar  avatar  avatar  avatar Mattia M. avatar Ninezero avatar  avatar  avatar Hossam ElAnsary avatar vbuterin2 avatar Borys Hlazman avatar

prop-types's Issues

Does 'prop-types' also check the node_modules?

I've literally searched my whole (own) codebase for every React.PropTypes call and replaced them with the new PropTypes call, but I still get the warning.

Is it possible this is because of a dependency in my node_modules that's still using the React.PropTypes call?

Build artifacts shouldn't be committed to source control

prop-types.js and prop-types.min.js are build artifacts and thus it doesn't really make sense for them to be committed to source control. Having them in source control makes diffs messier, unnecessarily bloats out the repository, and makes it easy for someone to forget to update them. They should be in the .gitignore.

Enable CI testing

Currently, there is no CI setup for running the unit tests against PRs. There should be!

Cannot find module "fbjs/lib/emptyFunction"

Uncaught Error: Cannot find module "fbjs/lib/emptyFunction"

factoryWithTypeCheckers.js?dcd5:12

.//prop-types//fbjs/lib/emptyFunction.js

Module build failed: Error: ENOENT: no such file or directory, open 'node_modules\prop-types\node_modules\fbjs\lib\emptyFunction.js'

.//prop-types//fbjs/lib/invariant.js

Module build failed: Error: ENOENT: no such file or directory, open 'node_modules\prop-types\node_modules\fbjs\lib\invariant.js'

.//prop-types//fbjs/lib/warning.js

Module build failed: Error: ENOENT: no such file or directory, open 'node_modules\prop-types\node_modules\fbjs\lib\warning.js

Using prop-types outside of React

Now that prop-types is a top-level package, it occurs to me that there are several use cases where this could be a useful library outside of React.

Use Case

Suppose, for example, you are writing an application with a REST interface that takes in some complicated JSON data, and queries MongoDB:

app.post("/api/getLastUserLogin", (req, res) => {
    // Expect req.body to be a `{username}` object.
    db.users.find({username: body.username})
    .then(users => {
        res.json(users[0] && users[0].lastLoginTime);
    });
});

Simple enough... But, oh noes! There are dark forces at work on the internet, and someone sends us this JSON body:

{"username": {"$ne": ""}}

MongoDB faithfully tries to load all 10 million of our users into memory, the server crashes, our company goes bankrupt, and our children starve.

But wait! prop-types to the rescue!

const LastUserLoginMessageType = {
    username: PropTypes.string.isRequired
}

app.post("/api/getLastUserLogin", (req, res) => {
    if(!PropTypes.validate(LastUserLoginMessageType, req.body)) {
        return res.status(400).send("Not today, hax0r!");
    }
    ...
});

Why this is awesome

There's a lot to recommend this. First, it's easy to check types without having to pull in some extra build step like TypeScript or Flow (especially nice on existing projects which don't already incorporate those technologies). Second, it's a syntax that many people are already very familiar with, because it's so widely used in React.

The challenge is, of course, that today prop-types is so tightly coupled to React. For starters, all of prop-types is disabled if NODE_ENV === 'production', which is an obvious problem, so there'd need to be some changes. Turning prop-types into a more general-purpose library should have advantages for React though, as it should make it easier to do things like #28.

API Proposal

This is just to give a vague idea of what I'm after here, there's lots of room for improvement on this, but:

PropTypes.isInvalid(typeSpec, value, options)

  • typeSpec is an object where keys are property names, and values are the associated PropType objects (e.g. {username: PropTypes.string}).
  • value is the object we're going to check.
  • options.context - See options.onValidationError().
  • options.onValidationError({path, expectedType, actualType, errorString, context}) - If this function returns a truthy value, then isInvalid() will return that value immediately. If this function throws, the the error will propagate all the way to the caller of isInvalid(). path is the path of the value being checked (e.g. "user.name"). expectedType is the type that was expected at this path (e.g. 'string'), actualType is the type we actually found. context is the options.context object passed to isInvalid(). errorString is an english-language ready made error string to describe what went wrong. The default implementation simply returns errorString.

I think this gives you flexibility to do quite a bit. The existing React use case, where we need to know if value came from props or context or whatever is solved by passing {location, componentName} along in the context, so onValidationError() can construct an appropriate string. React would set onValidationError: () => null when running production code.

One minor downside to this is it makes a webpacked production React app slightly bigger, since all this code that used to get optimized out is no longer going to be enclosed in NODE_ENV === 'production' checks. I can think of a couple of ways around that, but I'll leave that for future discussion.

errors after flow check

Hi all,
this issue are struggling me.

After a flow check there are these errors and i don0t know how to fix:

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:11
11: declare var array: React$PropType$Primitive<Array>;

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:18
18: declare var arrayOf: React$PropType$ArrayOf;
^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$ArrayOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:20
20: declare var instanceOf: React$PropType$InstanceOf;
^^^^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$InstanceOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:22
22: declare var objectOf: React$PropType$ObjectOf;
^^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$ObjectOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:23
23: declare var oneOf: React$PropType$OneOf;
^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$OneOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:24
24: declare var oneOfType: React$PropType$OneOfType;
^^^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$OneOfType. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:25
25: declare var shape: React$PropType$Shape;
^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$Shape. Could not resolve name

PropTypes throwing errors in production?

Currently in React 15.5.0, PropTypes called manually can result in an Error being thrown in production. This is due to the productionTypeChecker now being used in 15.5.0. We suspect that the boolean argument passed to invariant was either intended to be flipped, or warning was intended to be used instead here. Passing false to invariant will always throw an error.

We're currently seeing this occur in production as a result of using react-router v1.0.3, which expects PropType validators to return errors, and doesn't account for any errors being thrown.

process.env.NODE_ENV get replaced by 'development' in umd

The process.env.NODE_ENV gets replaced by 'development' in umd

In file prop-types/factoryWithTypeCheckers.js: (line 148)

  function createChainableTypeChecker(validate) {
    if (process.env.NODE_ENV !== 'production') {
      var manualPropTypeCallCache = {};
      var manualPropTypeWarningCount = 0;
    }

In umd bundle prop-types.js:

  function createChainableTypeChecker(validate) {
    if ("development" !== 'production') {
      var manualPropTypeCallCache = {};
      var manualPropTypeWarningCount = 0;
    }

making the condition always true, is it by design or a bug?

export `isValidElement`?

Could there be an entry point for isValidElement? I'd like to use it without depending on React :-)

Why PropType.boolean is function

Modal.propTypes = {visible: PropTypes.boolean}

Warning: Failed prop type: Modal: prop type visible is invalid; it must be a function, usually from React.PropTypes.

I think that the boolean type should be called 'boolean'
You can add boolean as alias for bool, for expected behavior PropTypes

I think if undefined PropType shouldn't be function

Question: should typed arrays be supported?

Hey. In my app I make heavy use of typed arrays. If I recall correctly, PropTypes treats them as objects, and having to say that my components required an object when they only took typed arrays felt like a bug-due-to-bad-documentation waiting to happen. So I made my own validation for it (see below).

However, I was wondering if typed array support shouldn't be part of the main package? I mean, I'm not really requesting it since I already fixed it for myself, and I know that their usage is relatively rare, but on the other hand: they are a core part of the language, so it feels a bit different from making custom validators for your own specific objects.

(And hey, even if you don't want to add it to the main prop-types package, at least the next person to look for typed array support can use something based on the code below)

export const TypedArrayProp = {
  any: (props, propName, componentName) => {
    let obj = props[propName];
    if (!(obj instanceof Float64Array ||
      obj instanceof Float32Array ||
      obj instanceof Int32Array ||
      obj instanceof Int16Array ||
      obj instanceof Int8Array ||
      obj instanceof Uint32Array ||
      obj instanceof Uint16Array ||
      obj instanceof Uint8Array ||
      obj instanceof Uint8ClampedArray)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a typed array.'
      );
    }
  },

  float64: (props, propName, componentName) => {
    if (!(props[propName] instanceof Float64Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Float64Array.'
      );
    }
  },

  float32: (props, propName, componentName) => {
    if (!(props[propName] instanceof Float32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Float32Array.'
      );
    }
  },

  float: (props, propName, componentName) => {
    if (!(props[propName] instanceof Float64Array ||
      props[propName] instanceof Float32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Float32Array or Float64Array.'
      );
    }
  },

  int32: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an Int32Array.'
      );
    }
  },

  int16: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int16Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an In16Array.'
      );
    }
  },

  int8: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int8Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an Int8Array.'
      );
    }
  },

  int: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int32Array ||
      props[propName] instanceof Int16Array ||
      props[propName] instanceof Int8Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an Int32Array, In16Array, or Int8Array.'
      );
    }
  },

  uint32: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint32Array.'
      );
    }
  },

  uint16: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint16Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint16Array.'
      );
    }
  },

  uint8: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint8Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint8Array.'
      );
    }
  },

  uint8clamped: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint8ClampedArray)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint8ClampedArray.'
      );
    }
  },

  uint: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint32Array ||
      props[propName] instanceof Uint16Array ||
      props[propName] instanceof Uint8Array ||
      props[propName] instanceof Uint8ClampedArray)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint32Array, Uint16Array, Uint8Array, or Uint8ClampedArray.'
      );
    }
  },
};

export { TypedArrayProp as default };

Access property type for documentation purposes at run time

Looking at how storybook and random questions on the internet it looks like it would be preferable to be able to pull the type of the property after it has been set.

I have a simple POC I can submit as a PR if that would be preferred. Code below as to what I would be expecting to have as an end result.

// this would be set with the validator
function getType() {
      return {
        type: type,
        subType: subType
      }
    }
propEnum.getType() => {type: "enum", subType: Array(4)}
propString.getType() => {type: "string", subType: undefined}

Is there a prop type for stateless functions that return a jsx component?

I wanted to use PropTypes.element to validate that the incoming prop was a component, but it is a stateless function that returns a JSX element. My eslint tells me that a function was supplied, but an element was expected. Is this an eslint issue, or should there be a prop type for a React stateless function?

Add ability to throw error instead of warning in tests

In tests it would be nice to throw an error if the property isn't of its expected type.

It would be nice if this could be scoped to our own components and not 3rd party ones using 3rd party components, but thats not necesary.

People are already turning console.warning calls to throw errors, so this would be a nice upgrade for them.

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

I keep getting warning errors when running my jest tests after updating to prop-types package:

PASS  __tests__/pages/about.test.js
  ● Console

    console.error node_modules/fbjs/lib/warning.js:36
      Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

package.json:

"dependencies": {
    "babel-eslint": "^7.2.1",
    "contentful": "^4.1.2",
    "csso": "^3.0.1",
    "element-class": "^0.2.2",
    "es6-promise": "^4.1.0",
    "eslint": "^3.18.0",
    "eslint-config-airbnb": "^14.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.10.3",
    "isomorphic-fetch": "^2.2.1",
    "lodash.camelcase": "^4.3.0",
    "lodash.merge": "^4.6.0",
    "memory-cache": "^0.1.6",
    "next": "^2.1.1",
    "randomstring": "^1.1.5"
  },
  "devDependencies": {
    "babel-jest ": "^19.0.0",
    "babel-plugin-transform-define": "^1.2.0",
    "babel-preset-es2015": "^6.24.0",
    "bunyan": "^1.8.10",
    "enzyme": "^2.8.0",
    "jest": "^19.0.2",
    "jest-cli": "^19.0.2",
    "lighthouse": "^1.6.3",
    "prop-types": "^15.5.6",
    "react": "^15.4.2",
    "react-addons-test-utils": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-markdown": "^2.4.6",
    "react-test-renderer": "^15.4.2",
    "sinon": "^2.1.0"
  },

About.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

Tried upgrading "react", "react-addons-test-utils", "react-dom" and "react-test-renderer" to 15.5.1 - Didn't work
Tried upgrading "react", "react-addons-test-utils", "react-dom" to 15.5.3 - Didn't work

Any help would be appreciated. Thanks

How to depend on this package?

Hi,
I have a package that has react as a peerDependency and provides PropTypes for the component it exports. Now that the prop-types is a separate package I would like to use it as a peerDependency as well but in an opt-in way (for users that use TypeScript, PropTypes are redundant). Is there a recommended way of handling this situation?

Thanks

Context around the change

Other than the fact mentioned on the blog We've extracted the built-in prop types to a separate package to reflect the fact that not everybody uses them. is there any other use of moving it to separate module?

Specify Valid Children Component Types

I was expecting to be able to use PropTypes.instanceOfto specify valid children types, like so:

    static propTypes = {
        children: PropTypes.arrayOf(PropTypes.oneOfType([ 
          PropTypes.instanceOf(ComponentOne), 
          PropTypes.instanceOf(ComponentTwo)
        ]))
    }

I got a relatively obscure error: Failed prop type: Right-hand side of 'instanceof' is not an object

After some searching, stumbled on: facebook/react#2979

The explanation/reason for closing being that instanceOf doesn't work on components. Okay, so would still like to achieve the end goal somehow. facebook/react#2979 (comment) is actually pretty slick.

Just specifying PropTypes.element is not sufficient, IMO.

I'm assuming this is a feature request, but maybe I'm overlooking something. TIA.

importing prop-types into a HOC is `undefined`

I'm creating a higher order component following the example on the React documentation website.

Here's a very simplified version of my HOC. This is in a file by itself.

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

export default function HigherOrderComponent(WrappedComponent) {
  class Wrapper extends React.Component {
    static propTypes = {
      children: PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.node),
        PropTypes.node,
      ]).isRequired,
    }

    componentDidMount() {
      // this.doStuff()
    }

    render() {
      return (
        <WrappedComponent
          {...this.props}
          wrapped={'Hey, I am a prop from the HOC!'}
        >{this.props.children}</WrappedComponent>);
    }
  }

  return Wrapper;
}

For some reason, PropTypes is "undefined". However, if I change every instance of PropTypes to React.PropTypes, it works just fine because it is accessing the PropTypes object from React.

It could be something related to babel / rollup, but I'm not sure. But I am suspicious of the issue being in Babel or Rollup because React gets passed through just fine.

Here is my .babelrc file:

{
  "presets": ["es2015-rollup", "react"],
  "plugins": [
    "transform-class-properties"
  ]
}

Checklist:

  • 'prop-types' is listed in my package.json under "dependencies"
  • I deleted my node_modules folder and ran npm i
  • import PropTypes from 'prop-types'; in other files seems to work just fine. I think it has to do with PropTypes being used in a function?

I have a repo with the issue on github if you want to see the full example. PM me if you want to check that out.

disallow null

When a type is optional it allows undefined or null. Unfortuantly prop-types eats the null and doesn't run any validators, so there doesn't seem to be a way to create a custom validator to disallow nulls.

Intersection types

I'm working on some tools related to moving back and forth between prop-types and Flow types.

One major omission is intersection types because there's no way to represent them in prop-types.

So I was thinking of a new validator eachOf which could be used for this:

let validator = PropTypes.eachOf([
  PropTypes.shape({ foo: PropTypes.number }),
  PropTypes.shape({ bar: PropTypes.number })
]);

test(validator, { foo: 1 }); // Error: Missing `bar`
test(validator, { bar: 2 }); // Error: Missing `foo`
test(validator, { foo: 1, bar: 2 }); // Works!

It'd work similar to PropTypes.oneOf except it's arr.every() instead of arr.some().

Using plain "PropTypes.bool" results in "warning.js:36 Warning: Failed prop type:"

Here is the snippet that gives me the error:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

import SmartField from './SmartField'

export default class MyComponent extends Component {
  static propTypes = {
    title: PropTypes.string,
    parameters: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    isStatic: PropTypes.bool,
    hidden: PropTypes.bool
  }

  render() {
    ...
  }
}

Makes no sense in my book that this is the only instance in my whole project where PropTypes.bool refuses to work

Warning: Failed prop type: MyComponent: prop type isStatic is invalid; it must be a function, usually from React.PropTypes.

Documentation about custom validators calling other validators

Hello,
I am wondering how to implement a custom validator which checks the type of an object.

The documentation is very clear for custom validators which do not call other validators, but it is quite unclear how validators should be called from custom validators. I have tried using PropTypes.checkPropTypes but couldn't make it happen.


Here is a solution that seems to be working:

// const customPropTypes = {...}

function (props, propName, componentName, ...rest) {
  if (props[propName]) {
    const { type } = props[propName]

    if (!type) {
      return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. Missing type.`)
    } else if (Object.keys(customPropTypes).indexOf(type) === -1) {
      return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. Unhandled type: ${type}.`)
    }

    return customPropTypes[type](props, propName, componentName, ...rest)
  }

  return null
}

Another challenge is to make the custom validator chainable in order to chain it with .isRequired. A blog post suggested to implement it this way:

const ANONYMOUS = '<<anonymous>>'

export default function createChainableTypeChecker (validate) {
  function checkType (isRequired, props, propName, componentName, ...rest) {
    componentName = componentName || ANONYMOUS

    if (props[propName] == null) {
      // var locationName = ReactPropTypeLocationNames[location]
      if (isRequired) {
        // return new Error(`Required ${locationName} \`${propName}\` was not specified in \`${componentName}\`.`)
        return new Error(`Required \`${propName}\` was not specified in \`${componentName}\`.`)
      }
      return null
    } else {
      return validate(props, propName, componentName, ...rest)
    }
  }

  var chainedCheckType = checkType.bind(null, false)
  chainedCheckType.isRequired = checkType.bind(null, true)

  return chainedCheckType
}

I commented out the part related to locationName as I could not figure out where ReactPropTypeLocationNames


Is it the way to solve to implement custom validators which call other validators ?

Optimize defaultProps with propTypes

Do you want to request a feature or report a bug?
feature,
PropTypes.string('default string');
What is the current behavior?
Two statics representing the same thing is kind of Trivial.

Component.propTypes = {
  foo: T.string,
  bar: T.number.isRequired,
};
Component.defaultProps = {
  foo: '12',
}

Sometimes people write useless code with this design. And you can't tell what is the author wanted.

Component.propTypes = {
  foo: T.string,
  bar: T.number.isRequired, // unnecessary isRequired.
};
Component.defaultProps = {
  foo: '12',
  bar: 12, // or unnecessary defaultProp.
}

What is the expected behavior?
Make defaultProps work with propTypes. One static other than two statics will be much easier for HOC and Developers to customize, modify or remove.

Component.propTypes = {
  foo: T.string('12'),
  bar: T.number.isRequired,
  // or
  foo: T.string.default('12'),
};

Unmet dependency for react 15.2.*

+-- [email protected]
+-- UNMET PEER DEPENDENCY [email protected]^0.14.0 || ^15.0.0
`-- UNMET PEER DEPENDENCY [email protected]^15.4.2

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected]^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN [email protected] requires a peer of [email protected]^15.4.2 but none was installed.
npm WARN [email protected] requires a peer of [email protected]^0.14.0 || ^15.0.0 but none was installed.
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.

Set defaultProps together with propTypes

Maybe this already exists, but right now I have to set defaultProps on my propTypes as a separate definition:

import PropTypes from 'prop-types';

...

MyComponent.propTypes = {
  propA: PropTypes.func,
  propB: PropTypes.bool.isRequired,
  propC: PropTypes.string
};

MyComponent.defaultProps = {
  propA: () => {},
  propC: 'Default String'
};

This can be really annoying for long lists of props. Not sure how this matches up with react philosophy, but it would be good to have a way to set types and defaults in one go to reduce code repetition and reduce opportunities for bugs:

PropTypes.setPropTypes(MyComponent, {
  propA: { type: PropTypes.func, default: () => {} },
  propB: PropTypes.bool.isRequired,
  propC: { type: PropTypes.string, default: 'Default String' }
})

use PropTypes from custom type function

is there any way to use the PropTypes validator from within custom props

i want to be able to do something like:

export const UnitPropType = (props, propName, componentName) => {
  const val = props[propName];
  const valid =
    PropType.oneOf(myKeys) ||
    PropTypes.instanceof(MediaQueryValue) ||
    PropTypes.arrayOf(MediaQueryValue);


  if (!valid) {
    return new Error(
      'Invalid prop `' + propName + '` supplied to' +
      ' `' + componentName + '`. Validation failed.'
    );
  }
};

`npm install prop-types --save` resolves to tarball

I'm not sure if this is normal for npm -- and I can't find much on google?

Issuing the following command:

> npm install prop-types --save
somePackage /Users/user/some-package
└── [email protected]

resolves in:

"prop-types": "https://registry.npmjs.org/prop-types/-/prop-types-15.5.8.tgz",

Issuing the following command

> npm install [email protected] --save
somePackage /Users/user/some-package
└── [email protected]  invalid

resolves in:

"prop-types": "^15.5.8",

This is not the case for all other packages. Just wanted to give a heads up in case it's something about the packaging of this module.

Why react should be declared as peerDependencies and prop-type as dependency ?

Hi Team, I've a question regarding the suggestion made in the readme on how to depend on prop-type:

https://github.com/reactjs/prop-types#how-to-depend-on-this-package

As a library maintainer both react and prop-type should be considered as external dependencies to my libraries as they should come from the environement using them and they should not be merged . So far I always thought that the peerDependency was the correct way of listing those dependencies (react and react-dom so far).
Now I'm a bit confused because you are suggesting to use prop-type as dependencies and not peerDependencies, what makes prop-types different to react ?

how to check what type does the checker function accept?

I have a react component imported and its .propTypes available, i.e. a map of all prop names to their checker function. Now I would like to get their accepting types.

One way I can think of is to feed each checker function with some value and find out. It should work totally fine for native value. The other is to extend each checker's prototype and record expected type info.

Is there a more proper and present way to do this?

prop-types doesn't validate props when using decorators

Not sure is it a problem with babel decorators transpiling or with prop-types (or something else) but when I use decorators I don't get errors in console about types mismatch. Code below won't raise any errors about 'fetchPaymentStatus' not being a string:

zrzut ekranu 2017-06-09 o 14 02 52

It will however raise error about not supplying required attribute.

If this is required I can prepare some test repo.

Object propType in oneOfType

Hi,
I get some weird issue with propTypes like this:

DateValidator.propTypes = {
    value: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.string,
        PropTypes.number,
    ]),
};

It gives me error:

Warning: Failed prop type: Invalid prop `value` supplied to `DateValidator`.

So useful :)

After some debug I see

PropTypeError {message: "Invalid prop `value` of type `date` supplied to `DateValidator`, expected `boolean`.", stack: ""}
PropTypeError {message: "Invalid prop `value` of type `date` supplied to `DateValidator`, expected `string`.", stack: ""}
PropTypeError {message: "Invalid prop `value` of type `date` supplied to `DateValidator`, expected `number`.", stack: ""}

So after some magic object is transformed to boolean. Why this can happen?

You can check it in my package

react: 15.5.4
prop-types: 15.5.8

Update:
As I see, the problem only with value prop, if I rename it, all works fine. But why this happening? Why something replace object with bool?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.