Created
April 4, 2019 13:27
-
-
Save codemzy/b3982f83dafa0a416ade11f5f8e23b56 to your computer and use it in GitHub Desktop.
Function including hoc to add consume multiple contexts in a component
This file contains hidden or 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 from 'react'; | |
// consumers | |
import { AlertConsumer } from './Alert'; // AlertContext.Consumer | |
import { UserConsumer } from './User'; //UserContext.Consumer | |
// -------------- CONTEXT FUNCTIONS -------------- // | |
// hoc for adding a context to a component as a consumer | |
const hocContextConsumer = function(ComposedComponent, ContextConsumer, name) { | |
return function (props) { | |
return ( | |
<ContextConsumer> | |
{context => { | |
let newContext = { [name]: context }; | |
return <ComposedComponent {...newContext} {...props} />; | |
}} | |
</ContextConsumer> | |
); | |
} | |
} | |
// function to add multiple contexts as props, use like... | |
// connectConsumers(YourComponent, { alert, user }); | |
export const connectConsumers = function(Component, contexts = {}) { | |
if (contexts.alert) { | |
Component = hocContextConsumer(Component, AlertConsumer, "alertContext"); | |
} | |
if (contexts.user) { | |
Component = hocContextConsumer(Component, UserConsumer, "userContext"); | |
} | |
return Component; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment