Skip to content

Instantly share code, notes, and snippets.

@nabeel-shakeel
Forked from thebinaryfelix/ProviderComposer.tsx
Created December 31, 2022 12:58
Show Gist options
  • Save nabeel-shakeel/c0b45227cd82c54f79a8a4f9663d371d to your computer and use it in GitHub Desktop.
Save nabeel-shakeel/c0b45227cd82c54f79a8a4f9663d371d to your computer and use it in GitHub Desktop.
Component for composing providers in React v18 with Typescript
export interface IProviderComposerProps extends React.PropsWithChildren {
/**
* Providers list
* */
with: React.FC<React.PropsWithChildren>[]
}
const ComposerFragment: React.FC<React.PropsWithChildren> = ({
children,
}): JSX.Element => <>{children}</>
const providerReducer =
(
ParentProvider: React.FC<React.PropsWithChildren>,
ChildProvider: React.FC<React.PropsWithChildren>,
) =>
({ children }: React.PropsWithChildren) =>
(
<ParentProvider>
<ChildProvider>{children}</ChildProvider>
</ParentProvider>
)
/**
* @Component
* @name ProviderComposer
* @description Component that receives a list of providers and composes them to a single component.
*/
export const ProviderComposer = (props: IProviderComposerProps) => {
const ComposedProviders = props.with.reduce(providerReducer, ComposerFragment)
return <ComposedProviders>{props.children}</ComposedProviders>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment