{"name":"mobx-react","version":"5.1.0-rc.3","description":"React bindings for MobX. Create fully reactive components.","main":"index.js","jsnext:main":"index.module.js","module":"index.module.js","react-native":"native.js","typings":"index","repository":{"type":"git","url":"git+https://github.com/mobxjs/mobx-react.git"},"scripts":{"prettier":"prettier --write \"**/*.js\" \"**/*.ts\"","test":"jest && npm run test:ts","test:ts":"tsc -p test/ts","test:travis":"npm run build && npm run jest && npm run test:ts","build":"node build-rollup.js && cp src/index.d.ts index.d.ts && cp src/index.d.ts native.d.ts && cp src/index.d.ts custom.d.ts","precommit":"lint-staged","watch":"jest --watch"},"author":{"name":"Michel Weststrate"},"license":"MIT","bugs":{"url":"https://github.com/mobxjs/mobx/issues"},"homepage":"https://mobxjs.github.io/mobx","peerDependencies":{"mobx":"^4.0.0","react":"^0.13.0 || ^0.14.0 || ^15.0.0 || ^16.0.0"},"devDependencies":{"@types/create-react-class":"^15.6.0","@types/node":"^9.0.0","@types/prop-types":"^15.5.2","@types/react":"^16.0.13","@types/react-dom":"^16.0.1","babel-core":"^6.26.0","babel-jest":"^22.0.4","babel-plugin-external-helpers":"^6.22.0","babel-plugin-transform-class-properties":"^6.24.1","babel-plugin-transform-decorators-legacy":"^1.3.4","babel-preset-es2015":"^6.24.1","babel-preset-es2015-rollup":"^3.0.0","babel-preset-react":"^6.24.1","babel-preset-stage-0":"^6.24.1","babelify":"^7.3.0","create-react-class":"^15.6.2","enzyme":"^3.3.0","enzyme-adapter-react-16":"^1.0.0","husky":"0.14.3","jest":"^22.0.5","jest-environment-jsdom":"^22.0.5","lint-staged":"^4.2.3","lodash":"^4.17.4","mobx":"^4.0.0","nscript":"^0.1.10","opn-cli":"^3.1.0","prettier":"^1.7.2","prop-types":"^15.6.0","react":"^16.0.0","react-dom":"^16.0.0","react-test-renderer":"^16.0.0","regenerator-runtime":"^0.11.1","request":"^2.83.0","rollup":"^0.50.0","rollup-plugin-alias":"^1.3.0","rollup-plugin-babel":"^3.0.2","rollup-plugin-commonjs":"^8.2.1","rollup-plugin-filesize":"^1.2.1","rollup-plugin-node-resolve":"^3.0.0","rollup-plugin-uglify":"^2.0.1","serve":"^6.1.0","typescript":"2.6"},"dependencies":{"hoist-non-react-statics":"^2.5.0","react-lifecycles-compat":"^3.0.2"},"keywords":["mobx","mobservable","react-component","react","reactjs","reactive"],"lint-staged":{"*.{ts,js}":["prettier --write","git add"]},"jest":{},"resolutions":{"@types/node":"9.6.7"},"readme":"# mobx-react\n\n[![Build Status](https://travis-ci.org/mobxjs/mobx-react.svg?branch=master)](https://travis-ci.org/mobxjs/mobx-react)\n[![Join the chat at https://gitter.im/mobxjs/mobx](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mobxjs/mobx?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n[![CDNJS](https://img.shields.io/cdnjs/v/mobx-react.svg)](https://cdnjs.com/libraries/mobx-react)\n\nPackage with React component wrapper for combining React with MobX.\nExports the `observer` decorator and some development utilities.\nFor documentation, see the [MobX](https://mobxjs.github.io/mobx) project.\nThis package supports both React and React Native.\n\n## Installation\n\n`npm install mobx-react --save`\n\nOr CDN: https://unpkg.com/mobx-react (namespace: `mobxReact`)\n\n```javascript\nimport { observer } from \"mobx-react\"\n// - or, for custom renderers without DOM: -\nimport { observer } from \"mobx-react/custom\"\n```\n\nThis package provides the bindings for MobX and React.\nSee the [official documentation](http://mobxjs.github.io/mobx/intro/overview.html) for how to get started.\n\n## Boilerplate projects that use mobx-react\n\n*   Minimal MobX, React, ES6, JSX, Hot reloading: [MobX-React-Boilerplate](https://github.com/mobxjs/mobx-react-boilerplate)\n*   TodoMVC MobX, React, ES6, JSX, Hot reloading: [MobX-React-TodoMVC](https://github.com/mobxjs/mobx-react-todomvc)\n*   Minimal MobX, React, Typescript, TSX: [MobX-React-Typescript-Boilerplate](https://github.com/mobxjs/mobx-react-typescript-boilerplate)\n*   Minimal MobX, React, ES6(babel), JSPM with hot reloading modules:\n    [jspm-react](https://github.com/capaj/jspm-react)\n*   React Native Counter: [Mobx-React-Native-Counter](https://github.com/bartonhammond/mobx-react-native-counter)\n\n## API documentation\n\n### observer(componentClass)\n\nFunction (and decorator) that converts a React component definition, React component class or stand-alone render function into a reactive component, which tracks which observables are used by `render` and automatically re-renders the component when one of these values changes.\nSee the [MobX](https://mobxjs.github.io/mobx/refguide/observer-component.html) documentation for more details.\n\n```javascript\nimport { observer } from \"mobx-react\"\n\n// ---- ES5 syntax ----\n\nconst TodoView = observer(\n    React.createClass({\n        displayName: \"TodoView\",\n        render() {\n            return <div>{this.props.todo.title}</div>\n        }\n    })\n)\n\n// ---- ES6 syntax ----\n\nconst TodoView = observer(\n    class TodoView extends React.Component {\n        render() {\n            return <div>{this.props.todo.title}</div>\n        }\n    }\n)\n\n// ---- ESNext syntax with decorators ----\n\n@observer\nclass TodoView extends React.Component {\n    render() {\n        return <div>{this.props.todo.title}</div>\n    }\n}\n\n// ---- or just use a stateless component function: ----\n\nconst TodoView = observer(({ todo }) => <div>{todo.title}</div>)\n```\n\n### `Observer`\n\n`Observer` is a React component, which applies `observer` to an anonymous region in your component.\nIt takes as children a single, argumentless function which should return exactly one React component.\nThe rendering in the function will be tracked and automatically re-rendered when needed.\nThis can come in handy when needing to pass render function to external components (for example the React Native listview), or if you\ndislike the `observer` decorator / function.\n\n```javascript\nclass App extends React.Component {\n    render() {\n        return (\n            <div>\n                {this.props.person.name}\n                <Observer>{() => <div>{this.props.person.name}</div>}</Observer>\n            </div>\n        )\n    }\n}\n\nconst person = observable({ name: \"John\" })\n\nReact.render(<App person={person} />, document.body)\nperson.name = \"Mike\" // will cause the Observer region to re-render\n```\n\nIn case you are a fan of render props, you can use that instead of children. Be advised, that you cannot use both approaches at once, children have a precedence.\nExample\n\n```javascript\nclass App extends React.Component {\n    render() {\n        return (\n            <div>\n                {this.props.person.name}\n                <Observer render={() => <div>{this.props.person.name}</div>} />\n            </div>\n        )\n    }\n}\n\nconst person = observable({ name: \"John\" })\n\nReact.render(<App person={person} />, document.body)\nperson.name = \"Mike\" // will cause the Observer region to re-render\n```\n\n### Global error handler with `onError`\n\nIf a component throws an error, this logs to the console but does not 'crash' the app, so it might go unnoticed.\nFor this reason it is possible to attach a global error handler using `onError` to intercept any error thrown in the render of an `observer` component.\nThis can be used to hook up any client side error collection system.\n\n```javascript\nimport { onError } from \"mobx-react\"\n\nonError(error => {\n    console.log(error)\n})\n```\n\n### Server Side Rendering with `useStaticRendering`\n\nWhen using server side rendering, normal lifecycle hooks of React components are not fired, as the components are rendered only once.\nSince components are never unmounted, `observer` components would in this case leak memory when being rendered server side.\nTo avoid leaking memory, call `useStaticRendering(true)` when using server side rendering. This makes sure the component won't try to react to any future data changes.\n\n### Which components should be marked with `observer`?\n\nThe simple rule of thumb is: _all components that render observable data_.\nIf you don't want to mark a component as observer, for example to reduce the dependencies of a generic component package, make sure you only pass it plain data.\n\n### Enabling decorators (optional)\n\nDecorators are currently a stage-2 ESNext feature. How to enable them is documented [here](https://github.com/mobxjs/mobx#enabling-decorators-optional).\n\n### Should I still use smart and dumb components?\n\nSee this [thread](https://www.reddit.com/r/reactjs/comments/4vnxg5/free_eggheadio_course_learn_mobx_react_in_30/d61oh0l).\nTL;DR: the conceptual distinction makes a lot of sense when using MobX as well, but use `observer` on all components.\n\n### About `shouldComponentUpdate`\n\nIt is possible to set a custom `shouldComponentUpdate`, but in general this should be avoided as MobX will by default provide a highly optimized `shouldComponentUpdate` implementation, based on `PureRenderMixin`.\nIf a custom `shouldComponentUpdate` is provided, it is consulted when the props changes (because the parent passes new props) or the state changes (as a result of calling `setState`),\nbut if an observable used by the rendering is changed, the component will be re-rendered and `shouldComponentUpdate` is not consulted.\n\nSince version 4, `mobx-react` will no longer trigger a re-rendering for non-observable objects that have been deeply changed.\n\n### `componentWillReact` (lifecycle hook)\n\nReact components usually render on a fresh stack, so that makes it often hard to figure out what _caused_ a component to re-render.\nWhen using `mobx-react` you can define a new life cycle hook, `componentWillReact` (pun intended) that will be triggered when a component is scheduled to be re-rendered because\ndata it observes has changed. This makes it easy to trace renders back to the action that caused the rendering.\n\n```javascript\nimport { observer } from \"mobx-react\"\n\n@observer\nclass TodoView extends React.Component {\n    componentWillReact() {\n        console.log(\"I will re-render, since the todo has changed!\")\n    }\n\n    render() {\n        return <div>{this.props.todo.title}</div>\n    }\n}\n```\n\n*   `componentWillReact` doesn't take arguments\n*   `componentWillReact` won't fire before the initial render (use `componentWillMount` instead)\n\n### `PropTypes`\n\nMobX-react provides the following additional `PropTypes` which can be used to validate against MobX structures:\n\n*   `observableArray`\n*   `observableArrayOf(React.PropTypes.number)`\n*   `observableMap`\n*   `observableObject`\n*   `arrayOrObservableArray`\n*   `arrayOrObservableArrayOf(React.PropTypes.number)`\n*   `objectOrObservableObject`\n\nUse `import { PropTypes } from \"mobx-react\"` to import them, then use for example `PropTypes.observableArray`\n\n### `Provider` and `inject`\n\n`Provider` is a component that can pass stores (or other stuff) using React's context mechanism to child components.\nThis is useful if you have things that you don't want to pass through multiple layers of components explicitly.\n\n`inject` can be used to pick up those stores. It is a higher order component that takes a list of strings and makes those stores available to the wrapped component.\n\nExample (based on the official [context docs](https://facebook.github.io/react/docs/context.html#passing-info-automatically-through-a-tree)):\n\n```javascript\n@inject(\"color\")\n@observer\nclass Button extends React.Component {\n    render() {\n        return <button style={{ background: this.props.color }}>{this.props.children}</button>\n    }\n}\n\nclass Message extends React.Component {\n    render() {\n        return (\n            <div>\n                {this.props.text} <Button>Delete</Button>\n            </div>\n        )\n    }\n}\n\nclass MessageList extends React.Component {\n    render() {\n        const children = this.props.messages.map(message => <Message text={message.text} />)\n        return (\n            <Provider color=\"red\">\n                <div>{children}</div>\n            </Provider>\n        )\n    }\n}\n```\n\nNotes:\n\n*   If a component asks for a store and receives a store via a property with the same name, the property takes precedence. Use this to your advantage when testing!\n*   If updates to an observable store are not triggering `render()`, make sure you are using Class methods for React lifecycle hooks such as `componentWillMount() {}`, using `componentWillMount = () => {}` will create a property on the instance and cause conflicts with mobx-react. See [mobx-react #195](https://github.com/mobxjs/mobx-react/issues/195) for more details.\n*   Values provided through `Provider` should be final, to avoid issues like mentioned in [React #2517](https://github.com/facebook/react/issues/2517) and [React #3973](https://github.com/facebook/react/pull/3973), where optimizations might stop the propagation of new context. Instead, make sure that if you put things in `context` that might change over time, that they are `@observable` or provide some other means to listen to changes, like callbacks. However, if your stores will change over time, like an observable value of another store, MobX will warn you. To suppress that warning explicitly, you can use `suppressChangedStoreWarning={true}` as a prop at your own risk.\n*   When using both `@inject` and `@observer`, make sure to apply them in the correct order: `observer` should be the inner decorator, `inject` the outer. There might be additional decorators in between.\n*   The original component wrapped by `inject` is available as the `wrappedComponent` property of the created higher order component.\n*   For mounted component instances, the wrapped component instance is available through the `wrappedInstance` property (except for stateless components).\n\n#### Inject as function\n\nThe above example in ES5 would start like:\n\n```javascript\nvar Button = inject(\"color\")(\n    observer(\n        React.createClass({\n            /* ... etc ... */\n        })\n    )\n)\n```\n\nA functional stateless component would look like:\n\n```javascript\nvar Button = inject(\"color\")(\n    observer(({ color }) => {\n        /* ... etc ... */\n    })\n)\n```\n\n#### Customizing inject\n\nInstead of passing a list of store names, it is also possible to create a custom mapper function and pass it to inject.\nThe mapper function receives all stores as argument, the properties with which the components are invoked and the context, and should produce a new set of properties,\nthat are mapped into the original:\n\n`mapperFunction: (allStores, props, context) => additionalProps`\n\nSince version 4.0 the `mapperFunction` itself is tracked as well, so it is possible to do things like:\n\n```javascript\nconst NameDisplayer = ({ name }) => <h1>{name}</h1>\n\nconst UserNameDisplayer = inject(stores => ({\n    name: stores.userStore.name\n}))(NameDisplayer)\n\nconst user = mobx.observable({\n    name: \"Noa\"\n})\n\nconst App = () => (\n    <Provider userStore={user}>\n        <UserNameDisplayer />\n    </Provider>\n)\n\nReactDOM.render(<App />, document.body)\n```\n\n_N.B. note that in this *specific* case neither `NameDisplayer` nor `UserNameDisplayer` needs to be decorated with `observer`, since the observable dereferencing is done in the mapper function_\n\n#### Using `propTypes` and `defaultProps` and other static properties in combination with `inject`\n\nInject wraps a new component around the component you pass into it.\nThis means that assigning a static property to the resulting component, will be applied to the HoC, and not to the original component.\nSo if you take the following example:\n\n```javascript\nconst UserName = inject(\"userStore\")(({ userStore, bold }) => someRendering())\n\nUserName.propTypes = {\n    bold: PropTypes.boolean.isRequired,\n    userStore: PropTypes.object.isRequired // will always fail\n}\n```\n\nThe above propTypes are incorrect, `bold` needs to be provided by the caller of the `UserName` component and is checked by React.\nHowever, `userStore` does not need to be required! Although it is required for the original stateless function component, it is not\nrequired for the resulting inject component. After all, the whole point of that component is to provide that `userStore` itself.\n\nSo if you want to make assertions on the data that is being injected (either stores or data resulting from a mapper function), the propTypes\nshould be defined on the _wrapped_ component. Which is available through the static property `wrappedComponent` on the inject component:\n\n```javascript\nconst UserName = inject(\"userStore\")(({ userStore, bold }) => someRendering())\n\nUserName.propTypes = {\n    bold: PropTypes.boolean.isRequired // could be defined either here ...\n}\n\nUserName.wrappedComponent.propTypes = {\n    // ... or here\n    userStore: PropTypes.object.isRequired // correct\n}\n```\n\nThe same principle applies to `defaultProps` and other static React properties.\nNote that it is not allowed to redefine `contextTypes` on `inject` components (but is possible to define it on `wrappedComponent`)\n\nFinally, mobx-react will automatically move non React related static properties from wrappedComponent to the inject component so that all static fields are\nactually available to the outside world without needing `.wrappedComponent`.\n\n#### Strongly typing inject\n\n##### With TypeScript\n\n`inject` also accepts a function (`(allStores, nextProps, nextContext) => additionalProps`) that can be used to pick all the desired stores from the available stores like this.\nThe `additionalProps` will be merged into the original `nextProps` before being provided to the next component.\n\n```typescript\nimport { IUserStore } from \"myStore\"\n\n@inject(allStores => ({\n    userStore: allStores.userStore as IUserStore\n}))\nclass MyComponent extends React.Component<{ userStore?: IUserStore; otherProp: number }, {}> {\n    /* etc */\n}\n```\n\nMake sure to mark `userStore` as an optional property. It should not (necessarily) be passed in by parent components at all!\n\nNote: If you have strict null checking enabled, you could muffle the nullable type by using the `!` operator:\n\n```\npublic render() {\n   const {a, b} = this.store!\n   // ...\n}\n```\n\n##### With Flow\n\nCurrently, there is a community-discussion around the best way to use `inject` with Flow. Join the discussion at [this gist](https://gist.github.com/vonovak/29c972c6aa9efbb7d63a6853d021fba9).\n\n#### Testing store injection\n\nIt is allowed to pass any declared store in directly as a property as well. This makes it easy to set up individual component tests without a provider.\n\nSo if you have in your app something like:\n\n```javascript\n<Provider profile={profile}>\n    <Person age={\"30\"} />\n</Provider>\n```\n\nIn your test you can easily test the `Person` component by passing the necessary store as prop directly:\n\n```\nconst profile = new Profile()\nconst mountedComponent = mount(\n   <Person age={'30'} profile={profile} />\n)\n```\n\nBear in mind that using shallow rendering won't provide any useful results when testing injected components; only the injector will be rendered.\nTo test with shallow rendering, instantiate the `wrappedComponent` instead: `shallow(<Person.wrappedComponent />)`\n\n## FAQ\n\n**Should I use `observer` for each component?**\n\nYou should use `observer` on every component that displays observable data.\nEven the small ones. `observer` allows components to render independently from their parent and in general this means that\nthe more you use `observer`, the better the performance become.\nThe overhead of `observer` itself is neglectable.\nSee also [Do child components need `@observer`?](https://github.com/mobxjs/mobx/issues/101)\n\n**I see React warnings about `forceUpdate` / `setState` from React**\n\nThe following warning will appear if you trigger a re-rendering between instantiating and rendering a component:\n\n```\nWarning: forceUpdate(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.`\n```\n\n-- or --\n\n```\nWarning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.\n```\n\nUsually this means that (another) component is trying to modify observables used by this components in their `constructor` or `getInitialState` methods.\nThis violates the React Lifecycle, `componentWillMount` should be used instead if state needs to be modified before mounting.\n\n## Internal DevTools Api\n\n### trackComponents()\n\nEnables the tracking from components. Each rendered reactive component will be added to the `componentByNodeRegistery` and its renderings will be reported through the `renderReporter` event emitter.\n\n### renderReporter\n\nEvent emitter that reports render timings and component destructions. Only available after invoking `trackComponents()`.\nNew listeners can be added through `renderReporter.on(function(data) { /* */ })`.\n\nData will have one of the following formats:\n\n```javascript\n{\n    event: 'render',\n    renderTime: /* time spend in the .render function of a component, in ms. */,\n    totalTime: /* time between starting a .render and flushing the changes to the DOM, in ms. */,\n    component: /* component instance */,\n    node: /* DOM node */\n}\n```\n\n```javascript\n{\n    event: 'destroy',\n    component: /* component instance */,\n    node: /* DOM Node */\n}\n```\n\n### componentByNodeRegistery\n\nWeakMap. Its `get` function returns the associated reactive component of the given node. The node needs to be precisely the root node of the component.\nThis map is only available after invoking `trackComponents`.\n","readmeFilename":"README.md","gitHead":"5446519c7c65bc2410f53721348c35856e3ea0ea","_id":"mobx-react@5.1.0-rc.3","_shasum":"98b94c01f8d02b51640f4dc545a4b3c0fd378101","_from":".","_npmVersion":"3.10.10","_nodeVersion":"6.10.0","_npmUser":{"name":"mweststrate","email":"mweststrate@gmail.com"},"dist":{"shasum":"98b94c01f8d02b51640f4dc545a4b3c0fd378101","tarball":"http://registry-npm.ywwl.com/mobx-react/download/mobx-react-5.1.0-rc.3.tgz","fileCount":22,"unpackedSize":658260,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJa51k/CRA9TVsSAnZWagAAsucP/iP/cH0DPDnybasd3lDE\nvRcJ11cGvEKMVpsQA7Ww5Lanrn38XLub9qwLqAnkZuIz2TBxmpr6gyqxihTk\n+hglVanyhl/izujPGxui+XVyZbYoUPuzrXzithIACG6BvWzAL+2kr7uelJN/\nQ4+FXy4ppnXDNEohquLXtYXut8i11eZlmMkHDOvy3aqLeDuOQ82VBaVPc6nq\nNqi2+eCmPdI45LYdEJVon7rcpNTiF/gpbLOZmgrwTiIE7W6Q++N9QZgECmEI\nAmQHcHlDdJrnsmuxCVIH2+qJxuvU0tJ4WDLWavZiUOoasafnuw7VitBEfDMW\nbu/7XOvxxXiIg1dqxlvvH/O1A1wvA9myRPKoJsu/9Y5folU7sdb2NRCurfJf\nCVQtJmrEg4/JbpM+pEgXw081E3Pw4dtN1t3Dfzk3s3OdTGvm6ZEOrqxH169s\nIw9dxnH/vxwkyBuE3xWWE1wMhjBXheGWP5ny0x1n9OiJg913CqFz0rQPDZLc\n04p1M8auDYYshzV7bGR7P5ZC/bgWVG21QUfeN3FlEzWC9DKaM5e847W4ysNg\nrBT7/HG721EopAnJBp1/ZZVo04Wji3zgkh4ealh9XG0+ntR0Zmh2eSi9E3Gh\nS+phqgzk9asZYHDEFiZrANZw0zmrqzJYpstPlbspAo/Ai7artGWhrH6G0zp7\np4r9\r\n=U4ty\r\n-----END PGP SIGNATURE-----\r\n","integrity":"sha512-cGD0Y3/KziT1J/6O7PGK7+OgEJzxjdZjWhkMCgtnaiJ7QvlMEWmzdIJHRkGspt5A9ezRiqUH44KizEIc9uJIwA==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFAbyr9zioQg7gHg9jHU77H5ExGdbMdP1PuZ8uIO3HhHAiEA7+7040pvGJbjzHtuLOjxFjAqKsAYTLHxz0IrlV46spQ="}],"size":170022,"noattachment":false,"key":"/mobx-react/-/mobx-react-5.1.0-rc.3.tgz"},"maintainers":[{"email":"mail@andykog.com","name":"andykog"},{"email":"strate@yandex.ru","name":"eshenbrener"},{"email":"mweststrate@gmail.com","name":"mweststrate"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/mobx-react_5.1.0-rc.3_1525111103480_0.3234337381720085"},"_hasShrinkwrap":false,"publish_time":1525111103660,"_cnpm_publish_time":1525111103660,"dist-tags":{"latest":"10.0.3"}}