Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ProviderComposer
function ProviderComposer({ contexts, children }) {
return contexts.reduceRight(
(kids, parent) =>
React.cloneElement(parent, {
children: kids,
}),
children
);
}
function ContextProvider({ children }) {
return (
<ProviderComposer
contexts={[<CheckoutProvider />, <LoginProvider />, <AlertProvider />]}
>
{children}
</ProviderComposer>
);
}
export { ContextProvider };
@tomekrozalski

This comment has been minimized.

Copy link

tomekrozalski commented Jun 22, 2019

Nice, but I have an issue: the providers (CheckoutProvider, LoginProvider and so on) are JSX components which requires children as props, isn't it? And here, in line 15 we are calling these providers without props. This makes our console looking bad ;) Yes, I know we can set defaultProps of providers to children: null, but it smells. It would be great if we could pass to context array (line 15) just providers as functions (contexts={[CheckoutProvider, LoginProvider, AlertProvider]})… The snippet is great anyway! Thanks for sharing :)

@nghiatv

This comment has been minimized.

Copy link

nghiatv commented Apr 22, 2020

I have same question as @tomekrozalski. So what is the answer here?

@tomekrozalski

This comment has been minimized.

Copy link

tomekrozalski commented Apr 22, 2020

@nghiatv I believe it is just linting / console / I don't know issue. On my next projects I didn't have this warning again. Now I use TypeScript and it does not complain at all for this script :)

@Alfrex92

This comment has been minimized.

Copy link

Alfrex92 commented May 14, 2020

Does anyone have the Typescript version of this snippet?

@tomekrozalski

This comment has been minimized.

Copy link

tomekrozalski commented May 14, 2020

@Alfrex92 I just use any:

type Props = {
  contexts: any;
};

const ProviderComposer: React.FC<Props> = ({ contexts, children }) =>
  contexts.reduceRight(
    (kids: React.ReactNode, parent: any) =>
      React.cloneElement(parent, {
        children: kids,
      }),
    children,
  );

const GlobalStateProvider: React.FC = ({ children }) => (
  <ProviderComposer contexts={[<Navigation />, <Authentication />, <Search />]}>
    {children}
  </ProviderComposer>
);
@Alfrex92

This comment has been minimized.

Copy link

Alfrex92 commented May 15, 2020

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.