Created
November 14, 2014 00:00
-
-
Save jquense/6508bfce7a248f85434e to your computer and use it in GitHub Desktop.
clone with props no extra 0.12
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var React = require('react') | |
, hasOwn = Object.prototype.hasOwnProperty | |
, version = React.version.split('.').map(parseFloat) | |
, RESERVED = { | |
className: resolve(joinClasses), | |
children: function(){}, | |
key: function(){}, | |
ref: function(){}, | |
style: resolve(extend) | |
}; | |
module.exports = function cloneWithProps(child, props) { | |
var newProps = mergeProps(props, child.props); | |
if (version[0] === 0 && version[1] === 12){ | |
MockLegacyFactory.isReactLegacyFactory = true | |
MockLegacyFactory.type = child.type | |
return React.createElement(MockLegacyFactory, newProps); | |
} | |
// 0.13+ | |
return React.createElement(child.type, newProps); | |
function MockLegacyFactory(){} | |
} | |
function mergeProps(currentProps, childProps) { | |
var newProps = extend(currentProps), key | |
for (key in childProps) { | |
if (hasOwn.call(RESERVED, key) ) | |
RESERVED[key](newProps, childProps[key], key) | |
else if ( !hasOwn.call(newProps, key) ) | |
newProps[key] = childProps[key]; | |
} | |
return newProps | |
} | |
function resolve(fn){ | |
return function(src, value, key){ | |
if( !hasOwn.call(src, key)) src[key] = value | |
else src[key] = fn(src[key], value) | |
} | |
} | |
function joinClasses(a, b){ | |
if ( !a ) return b || '' | |
return a + (b ? ' ' + b : '') | |
} | |
function extend() { | |
var target = {}; | |
for (var i = 0; i < arguments.length; i++) | |
for (var key in arguments[i]) if (hasOwn.call(arguments[i], key)) | |
target[key] = arguments[i][key] | |
return target | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment