Skip to content

Instantly share code, notes, and snippets.

@IvanGrimes
Last active January 29, 2020 11:16
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 IvanGrimes/8f7a0f6dae8923c6d6d440f61392e20e to your computer and use it in GitHub Desktop.
Save IvanGrimes/8f7a0f6dae8923c6d6d440f61392e20e to your computer and use it in GitHub Desktop.
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