Course contentsShow
← React
Lesson 294 of 2,3969. Class Components (Legacy Overview)Free lesson

Static Properties: defaultProps and propTypes

Learn how classes defined default props and runtime type checking as static class properties.

Static Properties: defaultProps and propTypes

You'll learn how class components declare default prop values and runtime type checking using static class properties.

The Core Idea

In class components, you can define static properties directly on the class itself (not on instances). The two most common are defaultProps and propTypes. These let you specify fallback values when props aren't provided and document what types your props should be—giving you automatic warnings in development if something's wrong.

defaultProps: Automatic Fallbacks

Think of defaultProps as a safety net. If a parent component forgets to pass a prop, your component automatically receives the default value instead of undefined:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

Greeting.defaultProps = {
  name: 'Guest'
};

// <Greeting /> renders "Hello, Guest!"
// <Greeting name="Sarah" /> renders "Hello, Sarah!"

You can also define defaults inside the class using the static keyword:

class Greeting extends React.Component {
  static defaultProps = {
    name: 'Guest'
  };

  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

Both syntaxes work identically—static just keeps everything together.

propTypes: Runtime Type Checking

The propTypes static property documents expected types and validates them during development (requires the separate prop-types package):

import PropTypes from 'prop-types';

class UserCard extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number
  };

  render() {
    return <div>{this.props.name} ({this.props.age})</div>;
  }
}

If you pass the wrong type or forget a required prop, React logs a console warning in development mode.

Key Takeaway: Class components use defaultProps for automatic fallback values and propTypes for development-time type warnings—both defined as static properties on the class.