Search code examples
javascriptreactjscomponents

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


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?


Solution

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

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