Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Sep 1, 2024. It is now read-only.
/prop-typesPublic archive

Runtime type checking for React props and similar objects

License

NotificationsYou must be signed in to change notification settings

facebook/prop-types

Runtime type checking for React props and similar objects.

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

Installation

npm install --save prop-types

Importing

importPropTypesfrom'prop-types';// ES6varPropTypes=require('prop-types');// ES5 with npm

CDN

If you prefer to excludeprop-types from your application and use itglobally viawindow.PropTypes, theprop-types package providessingle-file distributions, which are hosted on the following CDNs:

<!-- development version --><scriptsrc="https://unpkg.com/prop-types@15.6/prop-types.js"></script><!-- production version --><scriptsrc="https://unpkg.com/prop-types@15.6/prop-types.min.js"></script>
<!-- development version --><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script><!-- production version --><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>

To load a specific version ofprop-types replace15.6.0 with the version number.

Usage

PropTypes was originally exposed as part of the React core module, and iscommonly used with React components.Here is an example of using PropTypes with a React component, which alsodocuments the different validators provided:

importReactfrom'react';importPropTypesfrom'prop-types';classMyComponentextendsReact.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 infooptionalNode: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.jsoptionalElementType: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 typesoptionalUnion:PropTypes.oneOfType([PropTypes.string,PropTypes.number,PropTypes.instanceOf(Message)]),// An array of a certain typeoptionalArrayOf:PropTypes.arrayOf(PropTypes.number),// An object with property values of a certain typeoptionalObjectOf: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 shapeoptionalObjectWithShape:PropTypes.shape({optionalProperty:PropTypes.string,requiredProperty:PropTypes.number.isRequired}),// An object with warnings on extra propertiesoptionalObjectWithStrictShape:PropTypes.exact({optionalProperty:PropTypes.string,requiredProperty:PropTypes.number.isRequired}),requiredFunc:PropTypes.func.isRequired,// A value of any data typerequiredAny: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])){returnnewError('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])){returnnewError('Invalid prop `'+propFullName+'` supplied to'+' `'+componentName+'`. Validation failed.');}})};

Refer to theReact documentation for more information.

Migrating from React.PropTypes

Check outMigrating from React.PropTypes for details on how to migrate toprop-types fromReact.PropTypes.

Note that this blog postsmentions 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 independencies with a caret range.For example:

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

For libraries, wealso recommend leaving it independencies:

"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 youdon’t includePropTypes 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 withReact 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 withReact 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 fromReact.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 useprop-types package, but your version of React is incompatible with it. See theabove 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 standaloneprop-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 theprop-types package:

// Will not work with `prop-types` package!varerrorOrNull=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 seea warning rather than an error with this message, please check theabove section about compatibility.)

This is new behavior, and you will only encounter it when you migrate fromReact.PropTypes to theprop-types package. For the vast majority of components, this doesn’t matter, and if you didn’t seethis 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 useprop-types. If you temporarily need the old behavior, you can keep usingReact.PropTypes until React 16.

If you absolutely need to trigger the validation manually, callPropTypes.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 PropTypesPropTypes.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 thedevelopment version by importing/requiringprop-types/prop-types instead ofprop-types.

You might also see this error if you’re calling aPropTypes validator from your own customPropTypes validator. In this case, the fix is to make sure that you are passingall of the arguments to the inner function. There is a more in-depth explanation of how to fix iton this page. Alternatively, you can temporarily keep usingReact.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 tofollow 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 ifyou are using PropTypes without React then you may want to manually callPropTypes.checkPropTypes, like so:

constmyPropTypes={name:PropTypes.string,age:PropTypes.number,// ... define your prop validations};constprops={name:'hello',// is validage:'world',// not valid};// Let's say your component is called 'MyComponent'// Works with standalone PropTypesPropTypes.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(...) onlyconsole.errors a given message once. To reset the error warning cache in tests, callPropTypes.resetWarningCache()

License

prop-types isMIT licensed.

About

Runtime type checking for React props and similar objects

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp