UNPKG

react-with-hoc

Version:

Work with React and HOCs (Higher-Order Components)

75 lines 2.32 kB
import { ComponentType } from "react"; import { DependencyNames } from "../types/DependencyNames"; import { Fn, IntersectionFn, ToSchema } from "../types/Fn"; import { Hoc } from "../types/Hoc"; interface WithIfFn<PropName extends string, PropValue> extends Fn { return: [PropName, any] extends this["arg0"] ? this["arg0"] : this["arg0"] | [PropName, PropValue]; } interface WithIfHoc { <PropName extends string, PropValue = unknown>(propName: PropName, options?: { Else?: ComponentType<any>; }): Hoc<[WithIfFn<PropName, PropValue>]>; <DependencyProps extends {}, TDependencyNames extends DependencyNames<DependencyProps> = DependencyNames<DependencyProps>>(factory: (props: DependencyProps) => any, options: { Else?: ComponentType<any>; dependencyNames: TDependencyNames; }): Hoc<[IntersectionFn<ToSchema<DependencyProps>>]>; } /** * renders conditionally * * @experimental It could have a better name * * @example * const AdminDashboard: React.FC = () => { * return <>...</> * } * const SafeAdminDashboard = withIf<"isAdmin", boolean>("isAdmin")(AdminDashboard) * * // renders <AdminDashboard /> * <SafeAdminDashboard isAdmin={true} /> * * // renders null * <SafeAdminDashboard isAdmin={false} /> * * @example * const HappyScreen: React.FC = () => { * return <>...</> * } * const BlueErrorScreen: React.FC = () => { * return <>...</> * } * const NewComponent = withIf("error", { * Else: BlueErrorScreen * })(HappyScreen) * * // renders <HappyCase /> * <NewComponent error={null} /> * * // renders <BlueErrorScreen /> * <NewComponent error={new Error("some error")} /> * * @example * type HappinessLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; * const HappyScreen: React.FC = () => { * return <>...</> * } * const SadScreen: React.FC = () => { * return <>...</> * } * const MoodScreen = withIf<{ happinessLevel: HappinessLevel }>( * ({ happinessLevel }) => happinessLevel >= 5, * { * dependencyNames: ["happinessLevel"], * Else: SadScreen, * }, * )(HappyScreen); * * // renders <HappyScreen /> * <MoodScreen happinessLevel={10} /> * * // renders <SadScreen /> * <MoodScreen happinessLevel={3} /> */ export declare const withIf: WithIfHoc; export {}; //# sourceMappingURL=withIf.d.ts.map