Skip to main content

PropTypes Validation

Basic Types

import PropTypes from 'prop-types';

MyComponent.propTypes = {
string: PropTypes.string,
number: PropTypes.number,
boolean: PropTypes.bool,
array: PropTypes.array,
object: PropTypes.object,
function: PropTypes.func,
symbol: PropTypes.symbol,
node: PropTypes.node,
element: PropTypes.element
};

Required Props

MyComponent.propTypes = {
requiredString: PropTypes.string.isRequired,
requiredNumber: PropTypes.number.isRequired
};

Arrays and Objects

MyComponent.propTypes = {
// Array of specific type
numberArray: PropTypes.arrayOf(PropTypes.number),
objectArray: PropTypes.arrayOf(PropTypes.object),

// Object with specific shape
user: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number
}),

// Object with any key, specific value type
scores: PropTypes.objectOf(PropTypes.number)
};

Enums and Specific Values

MyComponent.propTypes = {
// Limited to specific values
status: PropTypes.oneOf(['active', 'inactive', 'pending']),

// Multiple possible types
id: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
};

Custom Validation

MyComponent.propTypes = {
customProp: function(props, propName, componentName) {
if (!/^[A-Z]/.test(props[propName])) {
return new Error(
`Invalid prop ${propName} supplied to ${componentName}. Must start with capital letter.`
);
}
}
};

React Elements

MyComponent.propTypes = {
// Any React element
element: PropTypes.element,

// Specific component type
component: PropTypes.elementType,

// Multiple elements
children: PropTypes.node
};

Collections

MyComponent.propTypes = {
// Instance of class
date: PropTypes.instanceOf(Date),

// Exact object shape
user: PropTypes.exact({
name: PropTypes.string,
age: PropTypes.number
})
};

Default Props

MyComponent.defaultProps = {
string: 'default',
number: 0,
array: [],
object: {}
};

Best Practices

  1. Always define propTypes for components that receive props
  2. Mark required props using isRequired
  3. Use shape for complex objects
  4. Provide defaultProps for optional props
  5. Use exact when strict object matching needed
  6. Document props with JSDoc comments

Development Only

PropTypes validation only runs in development mode. Removed in production builds for performance.