Last active
January 29, 2020 11:16
-
-
Save IvanGrimes/8f7a0f6dae8923c6d6d440f61392e20e to your computer and use it in GitHub Desktop.
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, useMemo } from 'react'; | |
import PropTypes from 'prop-types'; | |
export const makeInjectable = (Component, injectables) => { | |
const Context = createContext(injectables); | |
const useInjections = () => useContext(Context); | |
const WrappedComponent = ({ injections, ...props }) => { | |
const injected = useMemo(() => ({ ...injectables, ...injections }), [ | |
injections, | |
]); | |
return ( | |
<Context.Provider value={injected}> | |
<Component {...props} /> | |
</Context.Provider> | |
); | |
}; | |
WrappedComponent.defaultProps = { | |
...Component.defaultProps, | |
injections: {}, | |
}; | |
WrappedComponent.propTypes = { | |
...Component.propTypes, | |
injections: PropTypes.shape({ | |
[PropTypes.string]: PropTypes.element.isRequired, | |
}), | |
}; | |
WrappedComponent.displayName = `Injectable(${Component.displayName || | |
Component.name})`; | |
return { | |
Component: WrappedComponent, | |
useInjections, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment