### Installation for React 15+ Source: https://www.npmjs.com/package/prop-types Install the prop-types package for compatibility with React version 15.3.0 and higher. ```APIDOC ## Installation for React 15+ ### Description This package is compatible with **React 15.3.0** and higher. ### Method `npm install` ### Endpoint N/A ### Request Body N/A ### Request Example ```bash npm install --save react@^15.3.0 react-dom@^15.3.0 ``` ### Response N/A ``` -------------------------------- ### Installation for React 0.14 Source: https://www.npmjs.com/package/prop-types Install the prop-types package for compatibility with React version 0.14.9. ```APIDOC ## Installation for React 0.14 ### Description 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. ### Method `npm install` ### Endpoint N/A ### Request Body N/A ### Request Example ```bash # ATTENTION: Only run this if you still use React 0.14! npm install --save react@^0.14.9 react-dom@^0.14.9 ``` ### Response N/A ``` -------------------------------- ### Install prop-types for React 15+ Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Use this command for projects running React 15.3.0 or higher. ```bash npm install --save react@^15.3.0 react-dom@^15.3.0 ``` -------------------------------- ### Install prop-types via npm Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Use this command to add the package as a dependency to your project. ```bash npm install --save prop-types ``` -------------------------------- ### Install prop-types for React 0.14 Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Use this command to install the compatible version of prop-types if your project is still using React 0.14.9. ```bash # ATTENTION: Only run this if you still use React 0.14! npm install --save react@^0.14.9 react-dom@^0.14.9 ``` -------------------------------- ### Example of Manual PropTypes Validation Source: https://www.npmjs.com/package/prop-types?activeTab=code This example demonstrates how to use PropTypes.checkPropTypes to validate a set of props against defined prop types. It will log a warning if validation fails. ```javascript 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`. ``` -------------------------------- ### npm Dependencies for Libraries Source: https://www.npmjs.com/package/prop-types?activeTab=readme Example of how to add prop-types to a library's dependencies and peerDependencies in package.json. Ensure React is listed as a peer dependency. ```json { "dependencies": { "prop-types": "^15.5.7" }, "peerDependencies": { "react": "^15.5.0" } } ``` -------------------------------- ### npm Dependencies for Apps Source: https://www.npmjs.com/package/prop-types?activeTab=readme Example of how to add prop-types to your application's dependencies in package.json. Using a caret range is recommended for efficient deduplication. ```json { "dependencies": { "prop-types": "^15.5.7" } } ``` -------------------------------- ### Manual validation with PropTypes.checkPropTypes Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Example of manually checking prop types when not using React components. ```javascript 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`. ``` -------------------------------- ### Configure Package Dependencies Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Shows the recommended way to add prop-types to package.json for applications and libraries. ```json "dependencies": { "prop-types": "^15.5.7" } ``` ```json "dependencies": { "prop-types": "^15.5.7" }, "peerDependencies": { "react": "^15.5.0" } ``` -------------------------------- ### Include prop-types via unpkg CDN Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Load the library globally using the unpkg CDN for development or production environments. ```html ``` -------------------------------- ### Import prop-types Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Import the library using ES6 syntax or CommonJS require. ```javascript import PropTypes from 'prop-types'; // ES6 var PropTypes = require('prop-types'); // ES5 with npm ``` -------------------------------- ### Include prop-types via cdnjs CDN Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Load the library globally using the cdnjs CDN for development or production environments. ```html ``` -------------------------------- ### React Component with PropTypes Source: https://www.npmjs.com/package/prop-types?activeTab=code Demonstrates how to use various PropTypes validators with a React component. Ensure PropTypes is imported before use. ```javascript 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. ). 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.' ); } }) }; ``` -------------------------------- ### React Component with PropTypes Source: https://www.npmjs.com/package/prop-types?activeTab=readme Demonstrates various PropTypes validators for React components. Ensure PropTypes is imported. Custom validators should return an Error object on failure. ```javascript 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. ). 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.' ); } }) }; ``` -------------------------------- ### Validator Function Behavior Source: https://www.npmjs.com/package/prop-types?activeTab=dependencies Explanation of how validator functions behave with the prop-types package and how to handle direct calls. ```APIDOC ## Validator Function Behavior ### Description When you migrate components to use the standalone `prop-types` package, all validator functions will start throwing an error if you call them directly. This is to ensure they are not relied upon in production code and can be safely stripped to optimize bundle size. Code like this is still fine: ```javascript MyComponent.propTypes = { myProp: PropTypes.bool }; ``` However, code like this will not work with the `prop-types` package: ```javascript // 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 compatibility section for React versions. ### Handling Direct Calls If you absolutely need to trigger the validation manually, call `PropTypes.checkPropTypes()`. This function is safe to call in production as it will be replaced by an empty function. ### Development Version 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`. ``` -------------------------------- ### Define component propTypes Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Standard way to define prop types for a React component. ```javascript MyComponent.propTypes = { myProp: PropTypes.bool }; ``` -------------------------------- ### Define PropTypes for a React Component Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Demonstrates the usage of various built-in validators and custom validation functions within a React component's propTypes definition. ```javascript 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. ). 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.' ); } }) }; ``` -------------------------------- ### PropTypes.checkPropTypes Source: https://www.npmjs.com/package/prop-types How to manually trigger propType validation using PropTypes.checkPropTypes. ```APIDOC ## PropTypes.checkPropTypes ### Description 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: ### Method `PropTypes.checkPropTypes(propTypes, props, propName, componentName)` ### Endpoint N/A ### Parameters #### Arguments - **propTypes** (object) - Required - The propTypes definition object. - **props** (object) - Required - The props object to check. - **propName** (string) - Required - The name of the prop to check. - **componentName** (string) - Required - The name of the component. ### Request Example ```javascript 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`. ``` ### Response #### Success Response (200) N/A (This function triggers console warnings/errors, it does not return a value in the traditional sense). #### Response Example N/A ``` -------------------------------- ### PropTypes.resetWarningCache Source: https://www.npmjs.com/package/prop-types How to reset the warning cache for PropTypes.checkPropTypes, primarily for testing purposes. ```APIDOC ## PropTypes.resetWarningCache ### Description `PropTypes.checkPropTypes(...)` only `console.error`s a given message once. To reset the error warning cache in tests, call `PropTypes.resetWarningCache()` ### Method `PropTypes.resetWarningCache()` ### Endpoint N/A ### Request Body N/A ### Request Example ```javascript PropTypes.resetWarningCache(); ``` ### Response N/A ``` -------------------------------- ### Defining Component PropTypes Source: https://www.npmjs.com/package/prop-types?activeTab=dependencies This section outlines how to define prop validation for a React component using the various validators provided by the prop-types package. ```APIDOC ## PropTypes Definition ### Description Define the `propTypes` object on a React component class to enforce type checking for props at runtime. ### Available Validators - **PropTypes.array** - Validates an array. - **PropTypes.bigint** - Validates a BigInt. - **PropTypes.bool** - Validates a boolean. - **PropTypes.func** - Validates a function. - **PropTypes.number** - Validates a number. - **PropTypes.object** - Validates an object. - **PropTypes.string** - Validates a string. - **PropTypes.symbol** - Validates a symbol. - **PropTypes.node** - Validates anything that can be rendered (numbers, strings, elements, etc.). - **PropTypes.element** - Validates a React element. - **PropTypes.elementType** - Validates a React element type (function, string, or element-like object). - **PropTypes.instanceOf(Class)** - Validates an instance of a specific class. - **PropTypes.oneOf(['val1', 'val2'])** - Validates that the prop is one of the provided values. - **PropTypes.oneOfType([type1, type2])** - Validates that the prop matches one of the provided types. - **PropTypes.arrayOf(type)** - Validates an array of a specific type. - **PropTypes.objectOf(type)** - Validates an object with property values of a specific type. - **PropTypes.shape({ ... })** - Validates an object with a specific shape. - **PropTypes.exact({ ... })** - Validates an object with a specific shape and warns on extra properties. - **PropTypes.any** - Validates any data type. ### Usage Example ```javascript import PropTypes from 'prop-types'; MyComponent.propTypes = { optionalString: PropTypes.string, requiredNumber: PropTypes.number.isRequired, customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error('Validation failed.'); } } }; ``` ``` -------------------------------- ### Validator Function Behavior Source: https://www.npmjs.com/package/prop-types Explanation of how validator functions behave differently with the prop-types package compared to React.PropTypes. ```APIDOC ## Difference from `React.PropTypes`: Don’t Call Validator Functions ### Description 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: ```javascript MyComponent.propTypes = { myProp: PropTypes.bool }; ``` However, code like this will not work with the `prop-types` package: ```javascript // 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.) ### Method N/A ### Endpoint N/A ### Request Body N/A ### Response N/A ``` -------------------------------- ### Resetting the PropTypes Warning Cache Source: https://www.npmjs.com/package/prop-types?activeTab=code In testing environments, you can use PropTypes.resetWarningCache() to clear the cache of previously shown warnings, allowing them to be displayed again. ```javascript PropTypes.resetWarningCache() ``` -------------------------------- ### Manually trigger validation Source: https://www.npmjs.com/package/prop-types?activeTab=dependents Use PropTypes.checkPropTypes to manually trigger validation, which is safe to call in production. ```javascript // Works with standalone PropTypes PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent'); ``` -------------------------------- ### Directly calling validator functions Source: https://www.npmjs.com/package/prop-types?activeTab=dependents This pattern is unsupported in the standalone prop-types package and will throw an error. ```javascript // Will not work with `prop-types` package! var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop'); ``` -------------------------------- ### Directly Calling PropTypes Validators (Not Supported) Source: https://www.npmjs.com/package/prop-types?activeTab=code Directly calling PropTypes validator functions is not supported by the prop-types package and will throw an error. Use PropTypes.checkPropTypes() instead. ```javascript // Will not work with `prop-types` package! var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop'); ``` -------------------------------- ### Manually Triggering Validation with PropTypes.checkPropTypes Source: https://www.npmjs.com/package/prop-types?activeTab=code This function allows you to manually trigger prop type validation. It is safe to call in production. ```javascript // Works with standalone PropTypes PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent'); ``` -------------------------------- ### Error message for direct validator calls Source: https://www.npmjs.com/package/prop-types?activeTab=dependents The error message displayed when calling PropTypes validators directly. ```text Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.