React.js - default prop is not used with `null` is passed

Kosmetika picture Kosmetika · Jan 15, 2016 · Viewed 28.8k times · Source

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?

Answer

Jap Mul picture Jap Mul · Jan 15, 2016

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

<Component bedrooms={bedrooms || undefined} />