Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Created December 15, 2024 13:27
Show Gist options
  • Save jonathanconway/8a4144df3304505f720429e464641a4a to your computer and use it in GitHub Desktop.
Save jonathanconway/8a4144df3304505f720429e464641a4a to your computer and use it in GitHub Desktop.
Creates a function that applies a HOC to a React component
import { get, omit } from "lodash";
import { ComponentType } from "react";
export function createWithHOC<THOCProps, THOCName extends string>(
HOC: ComponentType<THOCProps>,
hocName: THOCName,
) {
return function withHOC<TLOCProps extends JSX.IntrinsicAttributes>(
LOC: ComponentType<TLOCProps>,
) {
return function ComponentWithLOC(
props: TLOCProps & Partial<Record<THOCName, THOCProps>>,
) {
const hocProps = props[hocName] as THOCProps;
if (hocProps) {
const hocPropsWithoutKey = omit(hocProps, "key") as THOCProps;
const hocKey = String(get(hocProps, "key"));
const locPropsWithoutHocProps = omit(props, hocName) as TLOCProps;
return (
<HOC {...hocPropsWithoutKey} key={hocKey}>
<LOC {...locPropsWithoutHocProps} />
</HOC>
);
} else {
return <LOC {...props} />;
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment