Top Related Projects
The repository for high quality TypeScript type definitions.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
A central repository for Flow library definitions
Runtime type system for IO decoding/encoding
Dead simple Object schema validation
Quick Overview
Prop-types is a runtime type-checking library for React props and similar objects. It helps developers catch bugs early by validating the types of props passed to React components, improving code reliability and maintainability.
Pros
- Enhances code quality by catching type-related errors during development
- Provides clear documentation of component interfaces
- Supports custom validators for complex prop types
- Lightweight and easy to integrate into existing React projects
Cons
- Adds runtime overhead, which may impact performance in large applications
- Not as comprehensive as static type checking systems like TypeScript
- Requires manual prop type definitions, which can be time-consuming
- Only checks props at runtime, not during compilation
Code Examples
- Basic prop type checking:
import PropTypes from 'prop-types';
function MyComponent({ name, age }) {
return <div>{name} is {age} years old</div>;
}
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
- Custom validator:
import PropTypes from 'prop-types';
function CustomComponent({ customProp }) {
return <div>{customProp}</div>;
}
CustomComponent.propTypes = {
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
}
};
- Array of specific type:
import PropTypes from 'prop-types';
function ListComponent({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
ListComponent.propTypes = {
items: PropTypes.arrayOf(PropTypes.string).isRequired
};
Getting Started
- Install prop-types:
npm install prop-types
- Import and use in your React component:
import PropTypes from 'prop-types';
function MyComponent({ name, age }) {
return <div>{name} is {age} years old</div>;
}
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
export default MyComponent;
Competitor Comparisons
The repository for high quality TypeScript type definitions.
Pros of DefinitelyTyped
- Comprehensive type definitions for a vast array of JavaScript libraries
- Community-driven with frequent updates and contributions
- Supports TypeScript, providing stronger type checking and better IDE integration
Cons of DefinitelyTyped
- Can be overwhelming due to its large size and numerous packages
- May have inconsistencies or outdated definitions for some libraries
- Requires additional setup and management in projects
Code Comparison
PropTypes (React):
import PropTypes from 'prop-types';
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
DefinitelyTyped (TypeScript):
interface MyComponentProps {
name: string;
age?: number;
}
const MyComponent: React.FC<MyComponentProps> = ({ name, age }) => {
// Component implementation
};
DefinitelyTyped provides static type checking at compile-time, while PropTypes performs runtime checks. DefinitelyTyped offers more robust type definitions and better IDE support, but PropTypes is simpler to set up and use in JavaScript projects. DefinitelyTyped is more suitable for large-scale TypeScript projects, while PropTypes is often preferred for smaller React applications or when gradually adding type checking to existing JavaScript codebases.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Pros of TypeScript
- Provides static typing for the entire JavaScript ecosystem, not just React props
- Offers more advanced type checking and inference capabilities
- Integrates seamlessly with modern IDEs for enhanced developer experience
Cons of TypeScript
- Steeper learning curve and more complex setup compared to prop-types
- Requires compilation step, which can increase build times
- May introduce additional complexity for smaller projects
Code Comparison
PropTypes example:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
TypeScript example:
interface Props {
name: string;
age?: number;
}
const MyComponent: React.FC<Props> = ({ name, age }) => {
// Component implementation
};
TypeScript offers a more robust and comprehensive type system that extends beyond just prop validation. It provides static typing for entire JavaScript projects, including React components. While prop-types is specifically designed for React prop validation, TypeScript's broader scope makes it suitable for larger, more complex applications.
PropTypes is easier to set up and use, especially for developers new to type systems. It's a lightweight solution that doesn't require a compilation step. However, TypeScript's advanced features and IDE integration can significantly improve developer productivity and code quality in the long run, particularly for larger projects.
A central repository for Flow library definitions
Pros of flow-typed
- Provides type definitions for popular libraries, enhancing static type checking
- Supports a wider range of JavaScript libraries and frameworks
- Community-driven, with frequent updates and contributions
Cons of flow-typed
- Requires Flow to be set up in the project, which can be more complex
- May have inconsistencies or outdated type definitions for some libraries
- Steeper learning curve for developers new to static typing
Code Comparison
prop-types:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
flow-typed:
// @flow
type Props = {
name: string,
age?: number
};
function MyComponent(props: Props) {
// ...
}
Summary
prop-types focuses on runtime type checking for React components, while flow-typed provides static type definitions for various JavaScript libraries. prop-types is easier to set up and use, especially for React developers, but offers less comprehensive type checking. flow-typed, when used with Flow, provides more robust static type checking across the entire project, but requires more setup and has a steeper learning curve. The choice between the two depends on the project's needs, team expertise, and desired level of type safety.
Runtime type system for IO decoding/encoding
Pros of io-ts
- Provides runtime type checking and static type inference
- Supports complex types and custom type definitions
- Offers better TypeScript integration and type safety
Cons of io-ts
- Steeper learning curve due to its functional programming approach
- Requires more setup and boilerplate code compared to prop-types
Code Comparison
prop-types:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
io-ts:
import * as t from 'io-ts';
const Person = t.type({
name: t.string,
age: t.union([t.number, t.undefined])
});
type PersonType = t.TypeOf<typeof Person>;
Summary
prop-types is a simple and widely-used runtime type checking library for React props. It's easy to set up and use but lacks static type checking.
io-ts offers more robust type checking with both runtime and compile-time benefits. It provides better TypeScript integration and supports complex type definitions. However, it has a steeper learning curve and requires more initial setup.
Choose prop-types for quick and simple prop validation in React projects. Opt for io-ts when you need more advanced type checking and want to leverage TypeScript's full potential in your application.
Dead simple Object schema validation
Pros of yup
- More powerful and flexible schema validation
- Supports asynchronous validation
- Can be used for both client-side and server-side validation
Cons of yup
- Larger bundle size and potentially slower performance
- Steeper learning curve due to more complex API
- Less focused on React-specific use cases
Code Comparison
prop-types:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
};
yup:
import * as Yup from 'yup';
const schema = Yup.object().shape({
name: Yup.string().required(),
age: Yup.number().positive().integer(),
});
Summary
prop-types is a lightweight, React-specific library for runtime type checking of props. It's simple to use and integrates seamlessly with React components. yup, on the other hand, is a more powerful and flexible schema validation library that can be used in various contexts, including form validation and API input validation. While yup offers more features and customization options, it comes with a larger bundle size and a steeper learning curve. The choice between the two depends on the specific needs of your project and the level of validation complexity required.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
prop-types
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/prop-types@15.6/prop-types.js"></script>
<!-- production version -->
<script src="https://unpkg.com/prop-types@15.6/prop-types.min.js"></script>
<!-- development version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<!-- production version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
To load a specific version of prop-types
replace 15.6.0
with the version number.
Usage
PropTypes was originally exposed as part of the React core module, and is commonly used with React components. Here is an example of using PropTypes with a React component, which also documents the different validators provided:
import React from 'react';
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
// ... do things with the props
}
}
MyComponent.propTypes = {
// You can declare that a prop is a specific JS primitive. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBigInt: PropTypes.bigint,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
// see https://reactjs.org/docs/rendering-elements.html for more info
optionalNode: PropTypes.node,
// A React element (ie. <MyComponent />).
optionalElement: PropTypes.element,
// A React element type (eg. MyComponent).
// a function, string, or "element-like" object (eg. React.Fragment, Suspense, etc.)
// see https://github.com/facebook/react/blob/HEAD/packages/shared/isValidElementType.js
optionalElementType: PropTypes.elementType,
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
// An array of a certain type
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
optionalProperty: PropTypes.string,
requiredProperty: PropTypes.number.isRequired
}),
// An object with warnings on extra properties
optionalObjectWithStrictShape: PropTypes.exact({
optionalProperty: PropTypes.string,
requiredProperty: PropTypes.number.isRequired
}),
requiredFunc: PropTypes.func.isRequired,
// A value of any data type
requiredAny: PropTypes.any.isRequired,
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
},
// You can also supply a custom validator to `arrayOf` and `objectOf`.
// It should return an Error object if the validation fails. The validator
// will be called for each key in the array or object. The first two
// arguments of the validator are the array or object itself, and the
// current item's key.
customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
if (!/matchme/.test(propValue[key])) {
return new Error(
'Invalid prop `' + propFullName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
})
};
Refer to the React documentation for more information.
Migrating from React.PropTypes
Check out Migrating from React.PropTypes for details on how to migrate to prop-types
from React.PropTypes
.
Note that this blog posts mentions a codemod script that performs the conversion automatically.
There are also important notes below.
How to Depend on This Package?
For apps, we recommend putting it in dependencies
with a caret range.
For example:
"dependencies": {
"prop-types": "^15.5.7"
}
For libraries, we also recommend leaving it in dependencies
:
"dependencies": {
"prop-types": "^15.5.7"
},
"peerDependencies": {
"react": "^15.5.0"
}
Note: there are known issues in versions before 15.5.7 so we recommend using it as the minimal version.
Make sure that the version range uses a caret (^
) and thus is broad enough for npm to efficiently deduplicate packages.
For UMD bundles of your components, make sure you donât include PropTypes
in the build. Usually this is done by marking it as an external (the specifics depend on your bundler), just like you do with React.
Compatibility
React 0.14
This package is compatible with React 0.14.9. Compared to 0.14.8 (which was released in March of 2016), there are no other changes in 0.14.9, so it should be a painless upgrade.
# ATTENTION: Only run this if you still use React 0.14!
npm install --save react@^0.14.9 react-dom@^0.14.9
React 15+
This package is compatible with React 15.3.0 and higher.
npm install --save react@^15.3.0 react-dom@^15.3.0
What happens on other React versions?
It outputs warnings with the message below even though the developer doesnât do anything wrong. Unfortunately there is no solution for this other than updating React to either 15.3.0 or higher, or 0.14.9 if youâre using React 0.14.
Difference from React.PropTypes
: Donât Call Validator Functions
First of all, which version of React are you using? You might be seeing this message because a component library has updated to use prop-types
package, but your version of React is incompatible with it. See the above section for more details.
Are you using either React 0.14.9 or a version higher than React 15.3.0? Read on.
When you migrate components to use the standalone prop-types
, all validator functions will start throwing an error if you call them directly. This makes sure that nobody relies on them in production code, and it is safe to strip their implementations to optimize the bundle size.
Code like this is still fine:
MyComponent.propTypes = {
myProp: PropTypes.bool
};
However, code like this will not work with the prop-types
package:
// Will not work with `prop-types` package!
var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop');
It will throw an error:
Calling PropTypes validators directly is not supported by the `prop-types` package.
Use PropTypes.checkPropTypes() to call them.
(If you see a warning rather than an error with this message, please check the above section about compatibility.)
This is new behavior, and you will only encounter it when you migrate from React.PropTypes
to the prop-types
package. For the vast majority of components, this doesnât matter, and if you didnât see this warning in your components, your code is safe to migrate. This is not a breaking change in React because you are only opting into this change for a component by explicitly changing your imports to use prop-types
. If you temporarily need the old behavior, you can keep using React.PropTypes
until React 16.
If you absolutely need to trigger the validation manually, call PropTypes.checkPropTypes()
. Unlike the validators themselves, this function is safe to call in production, as it will be replaced by an empty function:
// Works with standalone PropTypes
PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent');
See below for more info.
If you DO want to use validation in production, you can choose to use the development version by importing/requiring prop-types/prop-types
instead of prop-types
.
You might also see this error if youâre calling a PropTypes
validator from your own custom PropTypes
validator. In this case, the fix is to make sure that you are passing all of the arguments to the inner function. There is a more in-depth explanation of how to fix it on this page. Alternatively, you can temporarily keep using React.PropTypes
until React 16, as it would still only warn in this case.
If you use a bundler like Browserify or Webpack, donât forget to follow these instructions to correctly bundle your application in development or production mode. Otherwise youâll ship unnecessary code to your users.
PropTypes.checkPropTypes
React will automatically check the propTypes you set on the component, but if
you are using PropTypes without React then you may want to manually call
PropTypes.checkPropTypes
, like so:
const myPropTypes = {
name: PropTypes.string,
age: PropTypes.number,
// ... define your prop validations
};
const props = {
name: 'hello', // is valid
age: 'world', // not valid
};
// Let's say your component is called 'MyComponent'
// Works with standalone PropTypes
PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
// This will warn as follows:
// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
// `MyComponent`, expected `number`.
PropTypes.resetWarningCache()
PropTypes.checkPropTypes(...)
only console.error
s a given message once. To reset the error warning cache in tests, call PropTypes.resetWarningCache()
License
prop-types is MIT licensed.
Top Related Projects
The repository for high quality TypeScript type definitions.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
A central repository for Flow library definitions
Runtime type system for IO decoding/encoding
Dead simple Object schema validation
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot