@folo/withcontext
Version:
micro HOC compose component accepts custom context values as props
40 lines (33 loc) • 1.11 kB
JavaScript
;
var React = require('react');
/**
* HOC component
* Connect component to props
*
* @param {Component} targeted_component
* @param {Component} consumer_context
* @param {Array} contextProps contains props required from consumer
* @return {Component} - new component connected to context props
*/
function withcontext(_ref) {
var Component = _ref.Component,
Consumer = _ref.Consumer,
_ref$contextProps = _ref.contextProps,
contextProps = _ref$contextProps === void 0 ? [] : _ref$contextProps;
return function ComponentWithContext(props) {
return React.createElement(Consumer, null, function (context) {
var cn = contextProps.length > 0 ? {} : context;
/**
* if contextProps length is zero, pass all context props
* otherwise extract the required props
*/
if (contextProps.length > 0) {
contextProps.forEach(function (prop) {
cn[prop] = context[prop];
});
}
return React.createElement(Component, Object.assign({}, props, cn));
});
};
}
module.exports = withcontext;