Skip to content

Instantly share code, notes, and snippets.

@goldhand
Created August 19, 2017 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldhand/464451aec0194083202f36fedfc3b5a9 to your computer and use it in GitHub Desktop.
Save goldhand/464451aec0194083202f36fedfc3b5a9 to your computer and use it in GitHub Desktop.
Combines two components into one
/**
* components/Combo.js
*/
import React, {Component, PropTypes} from 'react';
/**
* Gets the displayname of a Component
* @param {ReactClass} WrappedComponent - component to get display name from
* @returns {string} Display name of WrappedComponent
*/
const getDisplayName = WrappedComponent =>
WrappedComponent.displayName || WrappedComponent.name || 'Component';
/**
* Gets props only if they are specified in propTypes
* @param {object} propTypes - React.PropTypes
* @param {object} props - component props
* @returns {object} filteredProps
*/
const filterProps = (propTypes, props) => {
const filteredProps = {};
for (const prop in props) {
if (Object.prototype.hasOwnProperty.call(propTypes, prop)) {
filteredProps[prop] = props[prop];
}
}
return filteredProps;
};
/**
* Combines two components into one component
* Combined component will take props from both components and pass them to the
* correct component.
* @param {ReactClass} ParentComponent - Component passed
* @param {ReactClass} ChildComponent - Component passed as children to Parent
* @returns {ReactClass} decorated component
*/
const Combo = ParentComponent => ChildComponent => {
const parentProps = filterProps.bind(null, ParentComponent.propTypes);
const childProps = filterProps.bind(null, ChildComponent.propTypes);
return class AuiWrapper extends Component {
displayName = `AUI(${getDisplayName(ChildComponent)})`;
static propTypes = {
children: PropTypes.any,
}
static defaultProps = {
children: null,
}
render() {
const {children} = this.props;
return (
<ParentComponent {...parentProps(this.props)}>
<ChildComponent {...childProps(this.props)}>
{children}
</ChildComponent>
</ParentComponent>
);
}
};
};
export default Combo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment