Created
September 10, 2016 11:09
-
-
Save miracle2k/3ed57dc312b64e05edfdaaa77d963f66 to your computer and use it in GitHub Desktop.
Split a properties object into multiple objects based on the propTypes definitions of components.
This file contains hidden or 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
/** | |
* Split a properties object into multiple objects based on the | |
* propTypes definitions of components. | |
* | |
* Usage: | |
* | |
* const [modalProps, dialogUIProps, otherProps] = | |
splitProps(this.props, Modal, DialogUI); | |
* | |
* Why? | |
* | |
* Sometimes, separating out which props to pass to a child component, | |
* and which to keep for youself can become very verbose. If a child | |
* component adds properties, you need to explicitly make wrappers | |
* support those new properities, too. | |
*/ | |
export function splitProps(props, ...subComponents) { | |
const result = []; | |
const usedProps = new Set(); | |
props = {...props}; | |
for (let component of subComponents) { | |
const propsForComponent = {}; | |
result.push(propsForComponent); | |
Object.keys(component.propTypes).forEach(propName => { | |
// Make sure a prop is not used in two sub components. | |
if (usedProps.has(propName)) { | |
console.warn(`${propName} is used twice!`); | |
} | |
usedProps.add(propName); | |
if (props[propName] === undefined) | |
return; | |
propsForComponent[propName] = props[propName]; | |
delete props[propName]; | |
}); | |
} | |
result.push(props); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment