facebook / prop-types

Runtime type checking for React props and similar objects
MIT License
4.48k stars 356 forks source link

Default Proptypes : Not able to set default prop value for object's property(s) if property is not defined #214

Open meetzaveri opened 6 years ago

meetzaveri commented 6 years ago

Do you want to request a feature or to report a bug

Both(Either of them). Report a Bug/Feature. Not sure if this would be a potential bug. This could be a feature when we can explicitly define a property via .defaultProps

What is current behavior (Re-produce) ?

props.derivedState is an object whose one of the property is randomString. It cannot be initialized i.e. set to default value using .defaultProps in case when I am not setting randomString in dereivedState object.(intentionally to test)

Basically object/array(or any other primitive element) can be set to default as per defaultProps functionality. But when setting property of an object, I am facing this issue that I cannot initialize it.

// in app.js
 <div>
    <h1>{this.props.derivedState.randomString}</h1>
     {/* PRINTS NOTHING (In case :  if randomString was not defined/set as property in object derivedState) */}
 </div>
...
App.defaultProps = {
  derivedState: {
    randomString: "Stranger"
  }
};

What is the expected behavior?

By doing this,

// in app.js
 <div>
    <h1>{this.props.derivedState.randomString}</h1>
     {/* PRINTS STRANGER (In case : if randomString was not defined/set as property in object derivedState) */}
 </div>
...
App.defaultProps = {
  derivedState: {
    randomString: "Stranger"
  }
};

the props.derivedState's property(i.e. randomString) can be set to default value to "Stranger".

Use cases (Codesandbox links):

I experienced that when instead of not setting randomString I completely didn't passed attribute derivedState(which is prop) which resulted in printing "Stranger" (randomString property ). This is reproduced in use case 2

ljharb commented 6 years ago

I'm confused; defaultProps only applies to top-level prop values, by design. If you pass an empty object, then the default simply won't apply.

This is a small part of the reason why flat props (ie, not an object) are preferred.

meetzaveri commented 6 years ago

This is a small part of the reason why flat props (ie, not an object) are preferred.

That's good to know. I'll keep in mind for better practices in this kind of structure