score:3

Using prop types is a good way of documenting the API for a component, so that other people know how it works without reading the code.

The way it's usually thought of is the component is guaranteed to render without errors if all the required props are supplied. The props that are not required would only enhance the component with additional functionality.

Consider this example

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      {avatarUrl && <img src={avatarUrl} />}
    </div>
  );
}

UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  avatarUrl: PropTypes.string
};

Now, if you want to render a default profile picture if it's not supplied, you could remove the conditional check inside the component and provide a default value instead.

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      <img src={avatarUrl} />
    </div>
  );
}

UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  avatarUrl: PropTypes.string
};

UserCard.defaultProps = {
  avatarUrl: "/assets/generic-picture.png"
};

Related Query

More Query from same tag