Skip to content

Instantly share code, notes, and snippets.

@devinrhode2
Created July 10, 2023 04:08
Show Gist options
  • Save devinrhode2/626dfd0a0ac914e402fb84f66f33f6d5 to your computer and use it in GitHub Desktop.
Save devinrhode2/626dfd0a0ac914e402fb84f66f33f6d5 to your computer and use it in GitHub Desktop.
withFooBarPropInjected.tsx with generics etc
import React from 'react';
import { useCheckoutSessionId } from '../useCheckoutSessionId';
type ComponentThatRequiresCheckoutSessionId<TProps> = (
yourBaseProps: TProps,
) => JSX.Element | null;
/** Patches return type */
type RemoveProp<
TComponent extends (...args: any) => any,
TPropKey extends string,
> = (
topLevelProps: Omit<Parameters<TComponent>[0], TPropKey>,
) => JSX.Element | null;
type ReturnedComp<TProps> = RemoveProp<
(topLevelProps: TProps) => Element | null,
'checkoutSessionId'
>;
export function injectCheckoutSessionIdProp<
TProps extends {
checkoutSessionId: string;
children: any;
[key: string]: any;
},
>(
ComponentThatRequiresCheckoutSessionId: ComponentThatRequiresCheckoutSessionId<TProps>,
): ReturnedComp<TProps> {
return function ComponentEnrichedWithCheckoutSessionIdProp(
topLevelProps: TProps,
) {
const checkoutSessionId = useCheckoutSessionId();
if (!checkoutSessionId) {
return null;
}
return (
<ComponentThatRequiresCheckoutSessionId
{...topLevelProps}
checkoutSessionId={checkoutSessionId}
/>
);
} as ReturnedComp<TProps>;
}