Skip to content

Instantly share code, notes, and snippets.

@radzserg
Last active July 12, 2019 08:31
Show Gist options
  • Select an option

  • Save radzserg/dd8161e81bb5227f3511a48be948009a to your computer and use it in GitHub Desktop.

Select an option

Save radzserg/dd8161e81bb5227f3511a48be948009a to your computer and use it in GitHub Desktop.
import * as React from "react";
import DIContext from "./DIContext";
import { IDIContainer } from "rsdi";
interface DIResolutionConfig {
[propName: string]: string;
}
type Without<T, K> = {
[L in Exclude<keyof T, K>]: T[L]
};
export default function withInjection<T, K>(
WrappedComponent: React.ComponentType<T>,
diConfig: DIResolutionConfig
): React.ComponentType<Without<T, keyof K>> {
const name = WrappedComponent.displayName || WrappedComponent.name;
class InjectionWrapper extends React.Component<any, any> {
static contextType = DIContext;
static displayName = `withInjection(${name})`;
static WrappedComponent = WrappedComponent;
render() {
const diContainer = this.context as IDIContainer;
const diProps: any = {};
Object.keys(diConfig).forEach((propName: string) => {
const definitionName = diConfig[propName];
diProps[propName] = diContainer.get(definitionName);
});
const { ...restProps } = this.props;
return <WrappedComponent {...diProps} {...(restProps as T)} />;
}
}
return InjectionWrapper;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment