Last active
December 7, 2020 13:37
-
-
Save n1ru4l/83597656ffbc83c2a5e1ac191f4a26b7 to your computer and use it in GitHub Desktop.
Having a lot of React Contexts?
This file contains 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 * 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