@samitouri / QOS-React-2 / commits / 58b3ae3136

Use Default Value for Undefined Props

Currently, default props as defined by `getDefaultProps` are only used if a prop is not specified (using `X in Y` check). However, this makes it difficult for composing components to pass along the state of not being defined, for example: render: function() { // If `this.props.someProp` is not set, `InnerThing` should use the default value. return <InnerThing someProp={this.props.someProp} />; } This changes the requirement for falling back to the default value to an undefined check (using `typeof X === 'undefined'`).

Tim Yung committed Oct 21, 2013 at 11:36 UTC 58b3ae3136e959350ece18a753392ab23ab177b6
2 files changed +24 -1
src/core/ReactCompositeComponent.js
+1 -1
@@ -668,7 +668,7 @@ var ReactCompositeComponentMixin = {
668 var propName;
669 var defaultProps = this._defaultProps;
670 for (propName in defaultProps) {
671 - if (!(propName in props)) {
671 + if (typeof props[propName] === 'undefined') {
672 props[propName] = defaultProps[propName];
673 }
674 }
src/core/__tests__/ReactCompositeComponent-test.js
+23
@@ -190,6 +190,29 @@ describe('ReactCompositeComponent', function() {
190
191 });
192
193 + it('should use default values for undefined props', function() {
194 + var Component = React.createClass({
195 + getDefaultProps: function() {
196 + return {key: 'testKey'};
197 + },
198 + render: function() {
199 + return <span />;
200 + }
201 + });
202 +
203 + var instance1 = <Component />;
204 + ReactTestUtils.renderIntoDocument(instance1);
205 + reactComponentExpect(instance1).scalarPropsEqual({key: 'testKey'});
206 +
207 + var instance2 = <Component key={undefined} />;
208 + ReactTestUtils.renderIntoDocument(instance2);
209 + reactComponentExpect(instance2).scalarPropsEqual({key: 'testKey'});
210 +
211 + var instance3 = <Component key={null} />;
212 + ReactTestUtils.renderIntoDocument(instance3);
213 + reactComponentExpect(instance3).scalarPropsEqual({key: null});
214 + });
215 +
216 it('should normalize props with default values', function() {
217 var Component = React.createClass({
218 propTypes: {key: ReactPropTypes.string.isRequired},