Skip to content

Commit

Permalink
Resolve default prop values in cloneElement
Browse files Browse the repository at this point in the history
In cloneElement, when key in input config is set to undefined, the associated
prop value should be resolved to default prop values
  • Loading branch information
truongduy134 committed Feb 8, 2016
1 parent 725a723 commit 73ffcd2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/isomorphic/classic/element/ReactElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,16 @@ ReactElement.cloneElement = function(element, config, children) {
props.children = childArray;
}

// Resolve default props
if (element.type && element.type.defaultProps) {
var defaultProps = element.type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}

return ReactElement(
element.type,
key,
Expand Down
23 changes: 23 additions & 0 deletions src/isomorphic/classic/element/__tests__/ReactElement-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,29 @@ describe('ReactElement', function() {
expect(inst2.props.prop).toBe(null);
});

it('should normalize props with default values in cloning', function() {
var Component = React.createClass({
getDefaultProps: function() {
return {prop: 'testKey'};
},
render: function() {
return React.createElement('span', null, this.props.prop);
},
});

var instance = React.createElement(Component);
var clonedInstance = React.cloneElement(instance, {prop: undefined});
expect(clonedInstance.props.prop).toBe('testKey');
var clonedInstance2 = React.cloneElement(instance, {prop: null});
expect(clonedInstance2.props.prop).toBe(null);

var instance2 = React.createElement(Component, {prop: 'newTestKey'});
var cloneInstance3 = React.cloneElement(instance2, {prop: undefined});
expect(cloneInstance3.props.prop).toBe('testKey');
var cloneInstance4 = React.cloneElement(instance2, {});
expect(cloneInstance4.props.prop).toBe('newTestKey');
});

it('throws when changing a prop (in dev) after element creation', function() {
var Outer = React.createClass({
render: function() {
Expand Down

0 comments on commit 73ffcd2

Please sign in to comment.