React PropType Utilities

1.1.1 · maintenance · verified Sun Apr 19

prop-types-extra is a utility library designed to augment React's prop-validation capabilities by providing an extended set of PropTypes. It builds upon the foundational `prop-types` package, offering specialized validators that address common and complex validation scenarios in React component development. Key validators include `all`, which enables combining multiple validation rules; `componentOrElement`, for validating props expecting either a React component or a DOM element reference; `deprecated`, a utility to log deprecation warnings for specific props; `elementType`, for ensuring a prop is a valid React element type (e.g., a string for a DOM element or a component constructor); and `isRequiredForA11y`, which enforces accessibility requirements. The package is currently at version 1.1.1. As a supplementary tool for `prop-types`, its release cadence is typically stable, with updates driven primarily by React's evolution or specific bug fixes rather than frequent feature additions. It differentiates itself by providing ready-to-use, advanced validation patterns, thereby simplifying the creation of robust and semantically correct React components.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the use of the `all` validator to combine standard PropTypes with a custom semantic validation function, showing how to enforce conditional prop dependencies for robust component usage.

import React from 'react';
import PropTypes from 'prop-types';
import { all } from 'prop-types-extra';

interface MyComponentProps {
  vertical: boolean;
  block: boolean;
}

const MyComponent: React.FC<MyComponentProps> = ({ vertical, block }) => {
  return (
    <div style={{
      display: block ? 'block' : 'inline',
      flexDirection: vertical ? 'column' : 'row'
    }}>
      My Component Content
    </div>
  );
};

MyComponent.propTypes = {
  vertical: PropTypes.bool.isRequired,
  block: all(
    PropTypes.bool.isRequired,
    ({ block, vertical }: MyComponentProps) => (
      block && !vertical ?
        new Error('`block` requires `vertical` to be set to have any effect') :
        null
    ),
  ) as PropTypes.Validator<boolean>, // Type cast for custom validator
};

// Example usage:
// In a React application, this component would be rendered:
// import ReactDOM from 'react-dom';
// const rootElement = document.getElementById('root');
// ReactDOM.render(<MyComponent vertical={true} block={true} />, rootElement);
// <MyComponent vertical={false} block={true} /> // Will log a propTypes warning in development

view raw JSON →