Sometimes, we may run into to the issue where default prop is not used when null is passed as the prop value in React.
In this article, we’ll look at how to fix the issue where default prop is not used when null is passed as the prop value in React.
Fix the Issue Where Default Prop is not Used When null is Passed as the Prop Value in React
To fix the issue where default prop is not used when null is passed as the prop value in React, we can pass in undefined instead of null as the value of the prop.
For instance, if we have the following default props in our component:
PropertyTitleLabel.defaultProps = {
bedrooms: 1,
propertyType: 'flat'
};
Then we write:
<PropertyTitleLabel bedrooms={bedrooms || undefined} />
to set bedrooms to 1 when the bedrooms prop value is undefined.
Conclusion
To fix the issue where default prop is not used when null is passed as the prop value in React, we can pass in undefined instead of null as the value of the prop.