kea-react
Version:
Componentes comunes de react
47 lines (41 loc) • 2.48 kB
text/typescript
//Algunos componentes de mas alto orden
import { mapState } from "react-mapstate";
import { Cookies } from "./cookies";
/**Convierte un componente controlado en uno no controlado, almacenando los valores no controlados en los cookies si es que el consumidor establece el prop cookieKey */
export function MakeUncontrolledCookies<TProps extends object>(valueKey: keyof TProps, onChangeKey: keyof TProps): (component: React.ComponentClass<TProps>) => React.ComponentClass<TProps & { cookieKey?: string }> {
type TState = { value: any };
type TPropsCookies = TProps & { cookieKey?: string };
const ret = mapState<TPropsCookies, TState>((props: TPropsCookies, state: TState, setState) => ({
//Ponemos el valor del state en el prop del value
[valueKey]: state.value,
//Pasamos en el onChange una función que establece el state y los cookies:
[onChangeKey]: (value: any) => {
setState({ value });
if (props.cookieKey)
Cookies.Set("uncontrolledCookies_" + props.cookieKey, value);
},
...(props as any)
}), (props) => ({ value: props.cookieKey && Cookies.Get("uncontrolledCookies_" + props.cookieKey) }))
return ret;
}
/**
* Convierte un componente controlado en uno no controlado, para el cual si se le pasa un value != undefined, se comporta como controlado
* @param valueKey Nombre de la propiedad del valor
* @param onChangeKey Nombre de la propiedad de la función de cambio en la forma (value) => void
*/
export function MakeUncontrolled<TProps extends object>(valueKey: keyof TProps, onChangeKey: keyof TProps, initialValue: any) {
type TState = { value?: any };
return mapState<TProps, TState>((props, state, setState) => Object.assign({
[valueKey]: state.value,
[onChangeKey]: (value: any) => setState({ value })
}, props), () => ({value: initialValue }));
}
/**Vuelve un componente controlado uno no controlado, donde en el estado inicial no se le pasara ningun valor al props de value */
export function mapStateUncontrolled<Props extends { value?: any, onChange?: (x: any) => void }>(component: React.ComponentClass<Props>) {
return mapState((props: Props, state, setState) => (
{
onChange: (value) => setState({ value: value }),
... (state.value ? { value: state.value } : {})
} as Props
), () => ({ value: undefined }))(component)
}