Reputation: 8603
I constantly struggle to understand, when exactly should I be using .isRequired
vs .defaultProps={...}
My thought is that, I think I should never ever really need to use isRequired, because it seems manually creating a bug that can break in the application because create isRequired automatically remove the need to add a corresponding default prop, that makes me feel uncomfortable just because it means I won't be able to expect a fail-safe value.
It definitely sounds an opinion based question, but I look for a better opinion that makes more sense if there is one.
Upvotes: 8
Views: 7982
Reputation: 10219
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"
};
Upvotes: 3