reactrators
Version:
A React library for composing and enhancing components with flexible and chainable functions. Simplify the process of injecting functionality and props into React components by providing a composable utility for building component enhancers.
40 lines (37 loc) • 1.31 kB
JavaScript
import { createElement } from 'react';
const _composeFns = (props, toCompose, opts) => {
return toCompose.reduce((acc, fn) => {
if (!Array.isArray(fn) && typeof fn !== "function") {
throw new Error("Hook must be a function or an array");
}
if (Array.isArray(fn) && fn.length !== 2) {
throw new Error("Hook must be an array with 2 elements");
}
let fnToCall = fn;
let params = void 0;
if (Array.isArray(fn)) {
if (typeof fn[0] !== "function" && typeof fn[1] !== "object") {
throw new Error("Hook must be an array with first element as a function and second element as an object");
}
const [fnArray, paramsArray] = fn;
fnToCall = fnArray;
params = paramsArray;
}
let fnInstanceParams = { ...params, ...props };
if (opts?.chainable) {
fnInstanceParams = { ...acc, ...params, ...props };
}
const fnInstance = fnToCall(fnInstanceParams);
acc = { ...acc, ...fnInstance };
return acc;
}, {});
};
const composable = (fn, opts) => (Component) => {
return (props) => {
const injectable = fn();
const toInject = _composeFns(props, injectable, opts);
return createElement(Component, { ...toInject, ...props });
};
};
export { composable as default };
//# sourceMappingURL=reactrators.mjs.map