Skip to content

Instantly share code, notes, and snippets.

@nmccready
Created April 4, 2019 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmccready/adb21bfee60cdf85a835af35cfa2a99d to your computer and use it in GitHub Desktop.
Save nmccready/adb21bfee60cdf85a835af35cfa2a99d to your computer and use it in GitHub Desktop.
withContext HOC providing Contexts
// usage example
const ChildComponent = ({ CanvasContext }) => {
const { setCanvasEl } = useContext(CanvasContext);
return <canvas ref={setCanvasEl} />;
}
const Component = ({ CanvasContext }) => {
const {canvasEl } = useContext(CanvasContext);
const contexts = { CanvasContext };
// .. do something with canvasEl
return (
<div>
<ChildComponent {...contexts} />
</div>
)
}
withContext({
stateName: 'canvasEl',
setStateName: 'setCanvasEl',
contextName: 'CanvasContext',
})(Component)
import React, { createContext, useState } from 'react';
/* For easy Nested State, intent is not for app wide state but for component shared state */
const withContext = ({
stateName,
setStateName,
stateHook = useState,
defaultState,
contextName,
}) => (BaseComponent) => {
const Context = createContext(defaultState);
const WithContextProvider = ({ children }) => {
const [state, stateSetterFn, ...otherHookReturns] = stateHook(defaultState);
return (
<Context.Provider
// maybe return array here like hooks
value={{
[stateName]: state,
[setStateName]: stateSetterFn,
otherHookReturns,
}}
>
{children}
</Context.Provider>
);
};
const WithContext = (props) => (
<WithContextProvider>
<BaseComponent {...{ ...props, [contextName]: Context }} />
</WithContextProvider>
);
WithContext.defaultProps = {};
return WithContext;
};
export default withContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment