prop-types

repository·main·Indexed 26 days ago

https://github.com/facebook/prop-types

Runtime type checking for React props and similar objects. It allows developers to document intended property types and receive development-time warnings when they are violated. The package provides validators for primitives, React elements, enums, and complex shapes, as well as utilities like checkPropTypes() for manual validation and resetWarningCache() for clearing warning logs.

Tokens
1.5K
Snippets
5
Records
9
Agent score
39%

What's inside prop-types

  1. Configure dependency requirements for libraries

    main

    When building a library, it is recommended to include prop-types in dependencies and react in peerDependencies to ensure compatibility and proper deduplication.

      "dependencies": {
        "prop-types": "^15.5.7"
      },
      "peerDependencies": {
        "react": "^15.5.0"
      }
  2. Install prop-types via npm

    main

    To add prop-types to your project, install it using npm. For applications, it is recommended to include it in your dependencies with a caret range to allow for efficient deduplication.

    npm install --save prop-types
  3. Use PropTypes validators in React components

    main

    Assign a propTypes object to your component to define expected types. Validators can be primitives, React elements, enums, or complex shapes. You can chain .isRequired to any validator to make the prop mandatory.

    import React from 'react';
    import PropTypes from 'prop-types';
    
    class MyComponent extends React.Component {
      render() {
        // ... do things with the props
      }
    }
    
    MyComponent.propTypes = {
      // Primitives
      optionalArray: PropTypes.array,
      optionalBool: PropTypes.bool,
      optionalNumber: PropTypes.number,
      optionalString: PropTypes.string,
    
      // React specific
      optionalNode: PropTypes.node,
      optionalElement: PropTypes.element,
      optionalElementType: PropTypes.elementType,
    
      // Advanced validators
      optionalInstance: PropTypes.instanceOf(Message),
      optionalEnum: PropTypes.oneOf(['News', 'Photos']),
      optionalUnion: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
      ]),
      optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
      optionalObjectOf: PropTypes.objectOf(PropTypes.number),
      optionalShape: PropTypes.shape({
        optionalProperty: PropTypes.string,
        requiredProperty: PropTypes.number.isRequired
      }),
      optionalExactShape: PropTypes.exact({
        optionalProperty: PropTypes.string,
        requiredProperty: PropTypes.number.isRequired
      }),
    
      // Required props
      requiredFunc: PropTypes.func.isRequired,
      requiredAny: PropTypes.any.isRequired,
    
      // Custom validators
      customProp: function(props, propName, componentName) {
        if (!/matchme/.test(props[propName])) {
          return new Error(
            'Invalid prop `' + propName + '` supplied to' +
            ' `' + componentName + '`. Validation failed.'
          );
        }
      }
    };
  4. Manually trigger validation with checkPropTypes()

    main

    Standalone prop-types validators cannot be called directly (e.g., PropTypes.string(val, ...) will throw an error). To manually trigger validation, use PropTypes.checkPropTypes(). This function is safe to call in production as it is replaced by an empty function.

    const myPropTypes = {
      name: PropTypes.string,
      age: PropTypes.number,
    };
    
    const props = {
      name: 'hello',
      age: 'world',
    };
    
    // Manually check validation
    PropTypes.checkPropTypes(myPropTypes, props, 'prop', 'MyComponent');
  5. Reset the warning cache with resetWarningCache()

    main
    Because PropTypes.checkPropTypes() only logs a specific error message once, you can call PropTypes.resetWarningCache() to clear the cache. This is particularly useful in test environments to ensure warnings are re-triggered.
  6. Check compatibility with React versions

    main

    The prop-types package has specific compatibility requirements:

    • React 0.14: Use react@^0.14.9 and react-dom@^0.14.9.
    • React 15+: Use react@^15.3.0 and react-dom@^15.3.0.

    Using incompatible versions may result in incorrect warning messages.

  7. Import prop-types for React component type checking

    main

    The prop-types package provides a set of type checkers used to validate the props passed to React components. The behavior of the package changes based on the NODE_ENV environment variable:

    • In development (NODE_ENV !== 'production'): The package provides full type checking and validation logic. It uses react-is to identify elements and enables throwOnDirectAccess to ensure developers follow correct usage patterns.
    • In production (NODE_ENV === 'production'): The package uses shims that effectively disable type checking to ensure zero performance overhead in production environments.