Created
April 4, 2019 16:13
-
-
Save nmccready/adb21bfee60cdf85a835af35cfa2a99d to your computer and use it in GitHub Desktop.
withContext HOC providing 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
// 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) |
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, 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