Skip to content

Instantly share code, notes, and snippets.

@codemzy
Created April 4, 2019 13:27
Show Gist options
  • Save codemzy/b3982f83dafa0a416ade11f5f8e23b56 to your computer and use it in GitHub Desktop.
Save codemzy/b3982f83dafa0a416ade11f5f8e23b56 to your computer and use it in GitHub Desktop.
Function including hoc to add consume multiple contexts in a component
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