glass-app-manager
Version:
Informatica's Glass Framework CLI for bootstrapping
45 lines (37 loc) • 1.62 kB
JavaScript
// @flow
import * as React from "react";
export default Object.assign(pushParentPropsToChildren);
/**
* Pushes relevant props to children. This method of passing props is intended for _small_
* components that won't have a lot of children. For components that you expect to have
* a lot of children for (e.g. table, shuttle, etc.) considering using a render prop,
* the context API, or redux.
* @param {object} children A reference to the children prop.
* @param {object} props The props source.
* @param {string[]} toPass A list of keys to pass to the children components.
* @param {object} [defaults] Any and all defaults you wish to pass to the
* children people that is not part of yours props object. This is a good use case
* for prop defaults which cannot be defined in `defaultProps` (e.g. callbacks
* on events which mutate state).
* @return {object[]} Cloned children prop with the props you want.
* @version 1.0.0
* @since 1.0.0
*/
export function pushParentPropsToChildren(
children: React.ChildrenArray<React.Node>,
props: {},
toPass: Array<string>,
defaults: {}
): React.ChildrenArray<React.Node> {
if (Array.isArray(children) && !children.length) {
throw new Error("Children reference must be defined!");
}
const childProps = toPass.reduce((acc, prop) => {
acc[prop] = props[prop];
return acc;
}, {});
if (defaults) {
Object.assign(childProps, defaults);
}
return React.Children.map(children, (child: React.Element<any>) => React.cloneElement(child, childProps));
}