UNPKG

react-remote-props

Version:
45 lines 1.5 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { useEffect, useState } from 'react'; import { BehaviorSubject } from 'rxjs'; /** * creates a wrapper around a component that allows to set props remotely * @param Component {ComponentType} the wanted component * @param initialProps {object} the props you want to inject * @returns array where the first value is the wrapped component and the second value is a function that setters the props. * @example ``` * const [Wrapper, setProps] = withProps(Button); * * // as component * <Wrapper /> * * // the setter * setProps({ * // props to change * }) * ``` */ export function remoteProps(Component, initialProps) { const subject = new BehaviorSubject({ ...Component.defaultProps, ...initialProps, }); const setProps = (valueOrFunc) => { const nextProps = { ...subject.value, ...(typeof valueOrFunc === 'function' ? valueOrFunc(subject.value) : valueOrFunc), }; subject.next(nextProps); }; const Wrapper = () => { const [props, setProps] = useState(subject.value); useEffect(() => { const subscription = subject.subscribe(setProps); return () => subscription.unsubscribe(); }, []); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return _jsx(Component, { ...props }); }; return [Wrapper, setProps]; } //# sourceMappingURL=index.js.map