SyntaxStudy
Sign Up
React PropTypes for Runtime Type Checking
React Beginner 1 min read

PropTypes for Runtime Type Checking

PropTypes is a runtime type-checking library that logs warnings to the browser console when a component receives props of the wrong type or is missing a required prop. Although TypeScript has largely superseded PropTypes for static analysis, PropTypes remain useful in plain JavaScript projects and as explicit documentation that tools like Storybook can pick up automatically. You attach a `propTypes` object to a component function to declare the expected type of each prop. The `prop-types` package ships independently of React and must be installed separately. Available validators include `PropTypes.string`, `PropTypes.number`, `PropTypes.bool`, `PropTypes.array`, `PropTypes.object`, `PropTypes.func`, and `PropTypes.node` (anything renderable). Appending `.isRequired` to any validator marks the prop as mandatory. `PropTypes.shape()` validates the structure of an object prop. PropTypes checks only run in development mode and are stripped in production builds, so they have no performance impact in production. For new projects, TypeScript is generally the better choice because it catches type errors at compile time rather than runtime, but understanding PropTypes deepens your understanding of React's prop system and is still found widely in existing codebases.
Example
// npm install prop-types
import PropTypes from 'prop-types';

function UserProfile({ name, age, email, role, address }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
      <p>Role: {role}</p>
      {address && <p>City: {address.city}, {address.country}</p>}
    </div>
  );
}

// Attach propTypes AFTER the component definition
UserProfile.propTypes = {
  name:    PropTypes.string.isRequired,       // required string
  age:     PropTypes.number.isRequired,       // required number
  email:   PropTypes.string.isRequired,
  role:    PropTypes.oneOf(['admin', 'editor', 'viewer']), // enum
  address: PropTypes.shape({                  // optional nested object
    city:    PropTypes.string,
    country: PropTypes.string,
  }),
};

// Default props for optional fields
UserProfile.defaultProps = {
  role: 'viewer',
  address: null,
};

// Missing required prop → console warning in dev:
// Warning: Failed prop type: The prop `email` is marked as required
// in `UserProfile`, but its value is `undefined`.

export default UserProfile;