react-hot-wire
motivation
I needed a React tool that would allow me to separate the view layer with other application layers. I wanted to be able to create services that are completely separated, that know nothing about the view. When I succeeded, there was a problem with injecting these services into individual components (at any application level). For this purpose a react-hot-wire
was created. It allows to define what services a given component needs, and enables convenient injection. Additionally, the component can react to changes in services by plugging its own listener into the service cycle.
installation
main package (to integrate with React)
$ npm install --save react-hot-wire
main dependency (to resolve DI container)
$ npm install --save hot-wire
simple usage
First we should define the service(s) to be solved by the hot-wire
module.
Example service:
// services/language.service.js _currentLanguage = 'en'; { return this_currentLanguage; }
Then by using hot-wire
we create the instances of the services and inject dependencies into the appropriate places (I suggest you see the hot-wire
tests). Then we pass the solved services to Provider
:
// index.js ;;;; const container = ; container;
Now you would like to inject into a component, at any level, an instance of a selected service. With help comes the wire
function, which in arguments accepts the component that is to have the service injected, and the array of services to be set in props
:
// components/language.component.js ;; { return languageService;} 'languageService' Language;
or simply:
;; ; { return <Wire services='languageService' render= <Language lang=languageService /> /> ;}
Now we have injected the selected service into the component, and we can take full advantage of its capabilities. As the service was injected by props, we have the possibility of convenient component testing, substitution of this service, etc.
advanced usage
listening to changes
// hoc/language.hoc.js ;; ;
// components/language.component.js ; { return lang;} Language;
- and small modification in the example service (extends for a
Service
)
- export default class LanguageService { + import { Service } from 'react-hot-wire';+ + export default class LanguageService extends Service {
API interface
<Provider>
- property
services: Object<string, Object>
- services after a resolved container
<Wire>
-
property
services: string[]
-
property
render: (services: Object<string, Object>): Component
wire()
wire(Component: Component, dependencies: string[]): Component
class Service
-
addChangeListener(changeListener: Function): Function
-
runChangeListeners(): void