Created
December 15, 2024 13:27
-
-
Save jonathanconway/8a4144df3304505f720429e464641a4a to your computer and use it in GitHub Desktop.
Creates a function that applies a HOC to a React component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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