(Updated with React Navigation ^v1.1.0)
This is a step by step guide to help you set up a react-native application, with react-navigation as your navigator, with MobX powering your intermediate data stores. The full source is on Github. Let’s get down to it.
*Edit: Feb 2018.
I’ve update the guide to React Navigation ^1.1.0. The only modification needed was to add a stub
addListener function to the helper. Of course, for the original purpose of the event subscription, please read up on the amazing work done by the author here. Personally I have no use for this (maybe I’m wrong?). Have a look and let me know.
Again, full runnable (with expo) and updated demo project source is here.
1. Setting up your RN app from scratch:
If you’re starting from scratch, definitely use the new
create-react-native-app command. You can always swap out Expo when you need more control and flexibility.
$ yarn global add create-react-native-app
$ create-react-native-app my-project
$ cd my-project
$ yarn start
yarn add react-navigation
3. Mobx and Mobx-react binding
yarn add mobx
yarn add mobx-react
4. Setup a basic StackNavigator
This basic setup includes an initial “Index” screen, and a “Search” screen. One can navigate / push a new screen onto the stack via calling the
navigate helper function and giving it a route name (ie. Search).
5. Replace RN-Navigation’s internal state with MobX
With the default navigator, the screen states are managed internally by the navigation package. It’s good practise to manage all your states with the same state manager, whether it’s Redux, MobX, or others. In this case, MobX should be the one taking care all the action dispatching and state management.
Basic Navigation store to observe the state, and patch over the dispatch and route it through MobX instead.
Make sure the observable is a
ref . For more info. on the modifier and what it means, read the MobX reference observables.
In your main App.js, wrap your rendered views with Provider and pass your exported store to it as a property.
The functionality shouldn’t change, but the underlying navigation state is now managed by MobX.
6. Passing back updates from a child screen
A commonly used functionality is to have a child screen update some params on the parent screen. For example, if the user searched for “Cat Gifs” on the search screen, and navigates back to Index, the index screen should show results for “Cat Gifs” and the navigation title should reflect the search term.
That’s it. Simple app with basic navigation, with state managed by MobX. Again, the full source is viewable on Github.
Sources and Inspirations:
react-native-navigation-mobx-demo - React native Navigation with MobX demo. Blog post write up ->
Does this package depend on Redux? Can we use it with Mobx? · Issue #34 · react-community/react…
react-navigation - Learn once, navigate anywhere