Learnitweb

React.proptypes.shape

React.PropTypes.shape is used in React to validate the shape of an object prop—that is, to specify what properties the object should have, and what types each property should be.

Note: PropTypes is no longer under React.PropTypes in newer React versions. Instead, you must import it from the prop-types package.

Example: Validating object shape with PropTypes.shape

import PropTypes from 'prop-types';

function UserProfile({ user }) {
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Age: {user.age}</p>
    </div>
  );
}

UserProfile.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired
  }).isRequired
};

Explanation:

  • PropTypes.shape({...}) specifies that user must be an object with:
    • a required name (string)
    • a required age (number)
  • The .isRequired at the end of user itself means the user object must be passed.

Nested Shape Example:

UserProfile.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string.isRequired,
    age: PropTypes.number,
    address: PropTypes.shape({
      city: PropTypes.string,
      zip: PropTypes.string
    })
  })
};

This allows deep validation of object structures.

When to use shape:

  • When a prop is an object and you want to validate its structure.
  • It improves maintainability and development-time feedback.