React-ioc
About
React-ioc is an implementation of InversifyJS for react applications.
It uses Context Api of React 16 to manage containers.
Features
-
Supports Hierarchical Dependency Injection.
-
Easy Api that supports Singleton pattern and Transient pattern.
-
Support for decorator and JSX based injection.
-
Automatic cleaning of injected properties on unmounting of React components.
-
Written with typescript i.e. has typings.
Installation
npm i @servicetitan/react-ioc --save
Documentation
@inject
Alias for @inject from InversifyJS.
@injectable
Alias for @injectable from InversifyJS.
Container
Alias for Container from InversifyJS.
@provide
A decorator used to inject the required information in the Provider in the current level of hierarchy.
@consumer
A HOC that can be used in order to consume IoC container in stateless components.
useDependencies
A Hook that can be used in order to consume IoC container in stateless components.
Provider
A React SFC equivalent to @provide
Examples
- Store
import { injectable } from '@servicetitan/react-ioc';
@injectable()
export class MySpecialStore {
public mySpecialValue: string;
constructor() {
this.mySpecialValue = 'My Special Text';
}
}
- Providing Container with
@provide
to a component
import {provide, consumer, injectDependency} from '@servicetitan/react-ioc';
@provide({
singletons: [MySpecialStore]
})
class MySpecialComponent extends React.Component {
render() {
return <MySpecialSubComponent />;
}
}
- Providing container with
<Provider>
<Provider singletons={[MySpecialStore]}>
<MySpecialComponent />
</Provider>
- Any child component can inject
MySpecialStore
with following syntax without using@provide
class MySpecialSubComponent extends React.Component {
@injectDependency(MySpecialStore)
public mySpecialStore: MySpecialStore;
render() {
return (
<span>
{this.mySpecialStore.mySpecialValue}
</span>
);
}
}
- For a non react component, we can inject values with
@inject
inside the container. Like:
class MySpecialConsumerStore {
private mySpecialStore: MySpecialStore;
constructor(@inject(MySpecialStore) mySpecialStore: MySpecialStore) {
this.mySpecialStore = mySpecialStore;
}
}
- Accessing container inside React FC.
// with consumer HOC
const MySpecialFC = consumer((props) => (
<div>
{props.container.get(MySpecialStore).mySpecialValue}
</div>
));
// with useDependencies hook
const MySpecialSFC = (props) => {
const [ mySpecialStore ] = useDependencies(MySpecialStore);
return (
<div>
{mySpecialStore.mySpecialValue}
</div>
);
};