Created
April 10, 2020 13:04
-
-
Save jonnolen/cda3da5b6c453bf49351239a4d5fdcf4 to your computer and use it in GitHub Desktop.
composing contexts... (i hate everything)
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 React, { createContext, useContext } from 'react' | |
// this thing does the composition. | |
function TurtlesContextHOC (contexts) { | |
let [FirstContext, ...Rest] = contexts | |
return (props) => { | |
console.log('rendering the TurtlesContext', FirstContext) | |
if (Rest.length === 0) { | |
return (<FirstContext> | |
{props.children} | |
</FirstContext>) | |
} else { | |
let RestContext = TurtlesContextHOC(Rest) | |
return (<FirstContext> | |
<RestContext> | |
{props.children} | |
</RestContext> | |
</FirstContext>) | |
} | |
} | |
} | |
// pretend each of these contexts are in different files, doing appropriately isolated things. | |
let ContextOne = createContext() | |
let ContextTwo = createContext() | |
let ContextThree = createContext() | |
let ContextFour = createContext() | |
let ContextOneProvider = ({ children }) => (<ContextOne.Provider value='CONTEXT ONE'> | |
{children} | |
</ContextOne.Provider>) | |
let ContextTwoProvider = ({ children }) => (<ContextTwo.Provider value='CONTEXT TWO'> | |
{children} | |
</ContextTwo.Provider>) | |
let ContextThreeProvider = ({ children }) => (<ContextThree.Provider value='CONTEXT THREE'> | |
{children} | |
</ContextThree.Provider>) | |
let ContextFourProvider = ({ children }) => (<ContextFour.Provider value='CONTEXT FOUR'> | |
{children} | |
</ContextFour.Provider>) | |
// any child or descendant that might need any of these contexts, also in separate file. | |
let Child = (props) => { | |
let c1 = useContext(ContextOne) | |
let c2 = useContext(ContextTwo) | |
let c3 = useContext(ContextThree) | |
let c4 = useContext(ContextFour) | |
return (<div> | |
{c1}, {c2}, {c3}, {c4} | |
</div>) | |
} | |
// root component that you would render int your app. | |
let TestComponent = TurtlesContextHOC([ContextOneProvider, ContextTwoProvider, ContextThreeProvider, ContextFourProvider]) | |
export let TestComponentRender = (props) => { | |
return (<TestComponent><Child /></TestComponent>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment