Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Last active December 7, 2020 13:37
Show Gist options
  • Save n1ru4l/83597656ffbc83c2a5e1ac191f4a26b7 to your computer and use it in GitHub Desktop.
Save n1ru4l/83597656ffbc83c2a5e1ac191f4a26b7 to your computer and use it in GitHub Desktop.
Having a lot of React Contexts?
import * as React from "react";
export type ComponentWithPropsTuple<TProps = any> = [
(props: TProps) => React.ReactElement,
TProps
];
/**
* This component allows rendering Components in a flat structure.
* Some components rely on a lot of differen context providers.
* Introducing a new level of nesting for each added context changes a lot of formatting of the nested code...
*/
export const FlatContextProvider = (props: {
value: Array<ComponentWithPropsTuple>;
children: React.ReactElement;
}): React.ReactElement => {
return props.value
.slice(0)
.reverse()
.reduce(
(innerNode, [Component, props]) => (
<Component {...props}>{innerNode}</Component>
),
props.children
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment