DEPRECATED
Now that MobX has Provider support, you should use that instead.
For React: mobx-react
For Inferno: mobx-inferno
mobx-connect
+ +
Super lightweight (2 kb uncompressed) MobX @connect
decorator for react/inferno components.
Similar to @connect
from react-redux.
Installation
npm install --save mobx-connect
How it works
By decorating your react/inferno component with @connect
2 things happen:
- Your components becomes observable (so no need to define @observable, since @connect does it for you).
- Your state and the store actions are inject into
this.context
.
Usage example (React.JS)
@connectComponent { const settings = thiscontextstate settingskey = !settingskey } { const settings = thiscontextstate return <div> <SettingsView/> <button onClick= this> Turn settingsfullscreen ? 'OFF' : 'ON' </button> <button onClick= this> Turn settingslogger ? 'OFF' : 'ON' </button> </div> } const SettingsView =
Usage example (inferno.JS)
@connect // Everything else same as with React...
Configuration
Ccreate a file called ContextProvider.js
.
We need to wrap our root component (App
in this case) around this ContextProvider
before rendering.
const React = const contextTypes = Component { return thispropscontext; } { return thispropschildren; } ContextProviderchildContextTypes = contextTypes;
Then we define our default state and our store methods which affect the state.
const observable = const context = // An observable mobx object state: store: // Your methods that affect the state here // You can make this object deeper for more complicated structures // or import from another file { contextstateusername = username; }
Finally we inject context into our app and render HTML on the browser
ReactDOM;
Usage with React-router
const React = const ReactDOM = const observable = const Router RouterContext browserHistory = const ContextProvider = // or where ever you put itconst routes = // or where ever you put it const context = state: store: {} { return <ContextProvider context=context> <RouterContext ...props /> </ContextProvider>} // Render HTML on the browserReactDOM
Usage with Inferno-router
const context = state: store: {}// Render HTML on the browserInfernoDOM ReactDOM
Author
https://github.com/nightwolfz