Components and decorators to connect react with inversify.
Installations
npm install inversify-rn
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
14.21.3
NPM Version
6.14.18
Score
67.8
Supply Chain
96.2
Quality
76
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (97.52%)
JavaScript (2.48%)
validate.email 🚀
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Developer
murat-mehmet
Download Statistics
Total Downloads
472
Last Day
1
Last Week
1
Last Month
11
Last Year
329
GitHub Statistics
Apache-2.0 License
69 Commits
1 Branches
1 Contributors
Updated on Nov 13, 2024
Bundle Size
7.70 kB
Minified
2.32 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.2.0
Package Id
inversify-rn@1.2.0
Unpacked Size
72.20 kB
Size
19.64 kB
File Count
13
NPM Version
6.14.18
Node Version
14.21.3
Published on
Sep 20, 2024
Total Downloads
Cumulative downloads
Total Downloads
472
Last Day
0%
1
Compared to previous day
Last Week
-66.7%
1
Compared to previous week
Last Month
-62.1%
11
Compared to previous month
Last Year
130.1%
329
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
inversify-react
Hooks and decorators for InversifyJS + React.
Table of Contents
- Motivation
- Installation
- Usage overview
- Provider
- React hooks
- React component decorators (for classes)
- Notes, tips
Motivation
TL;DR:
- InversifyJS, as IoC container, is great for automatic DI
- use it also in React
Installation
npm install --save inversify-react
yarn add inversify-react
...on top of your project with other modules already installed and configured
react
inversify
reflect-metadata
Keep in mind that Inversify uses decorators, which requires some setup for your build process.
Read more about decorators:
- https://github.com/inversify/InversifyJS#installation
- https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy
- https://www.typescriptlang.org/docs/handbook/decorators.html
inversify-react
also uses decorators, but only when used in Class Components.
Usage overview
Usage is pretty similar to React Context.
-
Wrap React component tree with
Provider
andContainer
frominversify-react
– just like React Context.Provider1import { Provider } from 'inversify-react'; 2... 3 4<Provider container={myContainer}> 5 ... 6</Provider>
-
Use dependencies from that container in child components
1import { resolve, useInjection } from 'inversify-react'; 2... 3 4// In functional component – via hooks 5const ChildComponent: React.FC = () => { 6 const foo = useInjection(Foo); 7 ... 8}; 9 10// or in class component – via decorated fields 11class ChildComponent extends React.Component { 12 @resolve 13 private readonly foo: Foo; 14 ... 15}
Provider
1<Provider container={myContainer}> 2 ... 3</Provider>
- provides contextual IoC container for children, similar to React Context.Provider
- can automatically establish hierarchy of containers in React tree when you use multiple Providers (e.g. in a big modular app)
- props:
container
- container instance or container factory functionstandalone
- (optional prop,false
by default) whether to skip hierarchy of containers. Could be useful if you already control container hierarchy and would like to ignore React-tree-based hierarchy.
1import * as React from 'react'; 2import { Container } from 'inversify'; 3import { Provider } from 'inversify-react'; 4 5// in functional component 6const AppOrModuleRoot: React.FC = () => { 7 return ( 8 <Provider container={() => { 9 const container = new Container(); 10 container.bind(Foo).toSelf(); 11 container.bind(Bar).toSelf(); 12 return container; 13 }}> 14 {/*...children...*/} 15 </Provider> 16 ); 17}; 18 19// or class component 20class AppOrModuleRoot extends React.Component { 21 22 // you can create and store container instance explicitly, 23 // or use factory function like in functional component example above 24 private readonly container = new Container(); 25 26 constructor(props: {}, context: {}) { 27 super(props, context); 28 29 const { container } = this; 30 container.bind(Foo).toSelf(); 31 container.bind(Bar).toSelf(); 32 } 33 34 render() { 35 return ( 36 <Provider container={this.container}> 37 {/*...children...*/} 38 </Provider> 39 ); 40 } 41}
React hooks
useInjection
1const foo = useInjection(Foo);
- very similar to React.useContext hook, resolves dependency by id
useOptionalInjection
1// e.g. Foo and Bar are not bound 2const foo = useOptionalInjection(Foo); // will return undefined 3// or 4const bar = useOptionalInjection(Bar, () => 'defaultBar'); // will return 'defaultBar'
- resolves optional dependency
- default value can be defined via lazy resolving function (2nd argument)
That function conveniently receives container as argument, so you could instantiate your default using container (e.g. if it has dependencies)1const foo = useOptionalInjection(Foo, () => myDefault); 2// foo === myDefault 3// ^ Foo | typeof myDefault
1const foo = useOptionalInjection(Foo, container => container.resolve(X));
useContainer
1const container = useContainer(); 2// or 3const foo = useContainer(container => container.resolve(Foo));
- low-level hook, resolves container itself
- has overload with callback to immediately resolve value from container, so could be used for more exotic API, e.g. named or tagged bindings
useAllInjections
1const bars = useAllInjections(Bar);
- @see multi-inject
For more examples, please refer to tests: test/hooks.tsx
React component decorators (for classes)
@resolve
1@resolve 2foo: Foo; 3 4// or strict and semantic, see tips below 5@resolve 6private readonly foo!: Foo;
- resolves service from container
- requires
reflect-metadata
andemitDecoratorMetadata
1// or pass service identifier explicitly 2// e.g. if you deal with interfaces and/or don't want to use field type (via reflect-metadata) 3@resolve(IFooServiceId) 4private readonly foo!: IFoo;
@resolve.optional
1@resolve.optional 2private readonly foo?: Foo;
- tries to resolve service from container, but returns
undefined
if service cannot be obtained - requires
reflect-metadata
andemitDecoratorMetadata
@resolve.optional(serviceId, defaultValue?)
- obtains service from container passed down in the React tree, returns
defaultValue
if service cannot be obtained
1class ChildComponent extends React.Component { 2 @resolve 3 private readonly foo!: Foo; 4 5 @resolve(Bar) 6 private readonly bar!: Bar; 7 8 @resolve.optional(Baz) 9 private readonly opt?: Baz; 10 11 ... 12} 13 14// you can also use dependency in constructor, 15// just don't forget to call super with context 16// @see https://github.com/facebook/react/issues/13944 17constructor(props: {}, context: {}) { 18 super(props, context); 19 console.log(this.foo.name); 20}
@resolve.all
1@resolve.all('Foo') 2private readonly foo!: Foo[];
- tries to resolve all services from container, fails if no services are bound to given service identifier
- requires
reflect-metadata
andemitDecoratorMetadata
, but cannot be used without explicitly specifying service identifier
@resolve.all(serviceId)
- obtains services from container passed down in the React tree
1class ChildComponent extends React.Component { 2 @resolve.all(Baz) 3 private readonly all!: Baz[]; 4 5 ... 6}
@resolve.optional.all
1@resolve.optional.all('Foo') 2private readonly foo!: Foo[];
- tries to resolve all services from container, returns empty array if none are registered
- requires
reflect-metadata
andemitDecoratorMetadata
, but cannot be used without explicitly specifying service identifier
@resolve.optional.all(serviceId)
- obtains services from container passed down in the React tree
1class ChildComponent extends React.Component { 2 @resolve.optional.all(Baz) 3 private readonly allorempty!: Baz[]; 4 5 ... 6}
Notes, tips
-
[TypeScript tip]
private readonly
for@resolve
-ed fields is not required, but technically it's more accurate, gives better semantics and all. -
[TypeScript tip]
!
for@resolve
-ed fields is needed for strictPropertyInitialization / strict flags (which are highly recommended). -
[InversifyJS tip] If you're binding against interface, then it might be more comfortable to collocate service identifier and type. With typed service identifier you get better type inference and less imports. Way better DX compared to using strings as identifiers.
1export interface IFoo { 2 // ... 3} 4export namespace IFoo { 5 export const $: interfaces.ServiceIdentifier<IFoo> = Symbol('IFoo'); 6}
1container.bind(IFoo.$).to(...); 2// ^ no need to specify generic type, 3// type gets inferred from explicit service identifier
1// in constructor injections (not in React Components, but in services/stores/etc) 2constructor(@inject(IFoo.$) foo: IFoo) 3 4// in React Class component 5@resolve(IFoo.$) 6private readonly foo!: IFoo; // less imports and less chance of mix-up 7 8// in functional component 9const foo = useInjection(IFoo.$); // inferred as IFoo 10

No vulnerabilities found.

No security vulnerabilities found.