Ad

React.js - Default Prop Is Not Used With `null` Is Passed

- 1 answer

I have default props in my React component:

PropertyTitleLabel.defaultProps = {
    bedrooms: 1,
    propertyType: 'flat'
};
PropertyTitleLabel.propTypes = {
    bedrooms: PropTypes.number,
    propertyType: PropTypes.string
};

But when I'm passing null to bedrooms like:

const bedrooms = null; // in real world API returns `null`
<Component bedrooms={bedrooms} />

It's not replaced with default prop :( Any ideas?

Ad

Answer

You can change the null value to undefined to use the default value.

<Component bedrooms={bedrooms || undefined} />
Ad
source: stackoverflow.com
Ad