Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
Kosmetika Avatar asked Jan 15 '16 10:01

Kosmetika


People also ask

What is the default value for a prop if no value is passed to it?

The logical OR operator || is used to set a fallback value for the version prop whenever it is not passed. A default value of 16 has been set for the version prop. With this change, everything now works as expected.

Can we have default values for props in React?

The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.

Can props be null React?

To specify null prop type in React, we can set null as the default prop value. We create the MyComponent component accepts the item prop. We set item 's type to be a string and is required. And then we specify that its default value is null so it can be set to null when nothing is set for item .

Why is my React prop undefined?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.


2 Answers

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

<Component bedrooms={bedrooms || undefined} /> 
like image 77
Jap Mul Avatar answered Sep 23 '22 21:09

Jap Mul


I think there's a distinction between null and undefined that is made when dealing with the defaultProps. The null value could be intended behavior and thus isn't replaced by your defaults, while undefined is not and will be replaced.

As stated in the docs

[...] used to ensure that this.props.value will have a value if it was not specified by the parent component.

Here is a related issue.

like image 44
Preview Avatar answered Sep 26 '22 21:09

Preview