Package Exports
- react-ioc
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-ioc) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
React IOC
Hierarchical Dependency Injection for React
Features
- Hierarchical Injection
- Can inject ES6 classes and React components
- Can inject dependencies using React Hooks
- Automatically calls
.dispose()
on created class instances when Reat unmoutsProvider
component - ES6, CommonJS and UMD bundles
- Declarations for TypeScript and Flow
- Type Safe even in JavaScript (with TypeScript
--checkJs
mode) - Tiny: only 1 KB (min+gzip)
Documentation
- @provider
- @inject (@service)
- getInstance (getService)
- getFunction (getComponent)
- useInstance (useService) React Hook
- useFunction (useComponent) React Hook
- makeInstance
Example
import React, { Component } from "react";
import { provider, inject } from "react-ioc"
import { obserbvable, action } from "mobx";
import { observer } from "mobx-react";
class DataContext {
users = observable.map<number, User>();
posts = observable.map<number, Post>();
}
class PostService {
@inject dataContext: DataContext;
@action
createPost(user: User) {
const post = new Post({ id: uniqueId() });
this.dataContext.posts.set(post.id, post);
return post;
}
}
@observer
class PostEditor extends Component {
@inject postService: PostService;
render() {
// ...
}
}
@provider(DataContext, PostService)
class App extends Component {
render() {
// ...
}
}
@provider (alias @Provider)
TODO
@inject (alias @service, @Inject, @Service)
TODO
getInstance (alias getService)
TODO
getFunction (alias getComponent)
TODO
useInstance (alias useService) React Hook
import { useService, useServices } from "react-ioc";
const MyButton = props => {
const myService = useService(MyService);
return <button onClick={() => myService.doSomething()}>Ok</button>
}
const MyWidget = props => {
const [fooService, barService] = useServices(FooService, BarService);
return <div><MyButton /></div>
}
useFunction (alias useComponent) React Hook
TODO
makeInstance (alias makeService)
TODO
Usage
> npm install --save react-ioc
Requirements: IE9+, ES6 Map polyfill (like for React).
UMD build
<script crossorigin src="https://unpkg.com/react-ioc/dist/index.umd.min.js"></script>
const { provider, inject } = window.ReactIOC;