Skip to content

Instantly share code, notes, and snippets.

@AntonPuko
Last active August 30, 2018 03:59
Show Gist options
  • Save AntonPuko/4b9af98b5b16e4b61dfeac2565e83c49 to your computer and use it in GitHub Desktop.
Save AntonPuko/4b9af98b5b16e4b61dfeac2565e83c49 to your computer and use it in GitHub Desktop.
integrating react-navigation with mobx
import type { NavigationAction, NavigationParams } from 'react-navigation';
import * as React from 'react';
import { BackHandler } from 'react-native';
import { NavigationActions, StackNavigator, addNavigationHelpers } from 'react-navigation';
import { action, observable } from 'mobx';
import { observer } from 'mobx-react';
const RootNavigator = StackNavigator(
{
splash: { screen: SplashScreen },
login: { screen: LoginScreen },
},
);
const rootRouter = RootNavigator.router;
class $NavigationStore {
@observable
navigationState = rootRouter.getStateForAction(
rootRouter.getActionForPathAndParams('splash'),
);
// it can be more helpers like this, for things like goBack, reset, etc.
navigate = (routeName: string, params?: NavigationParams): void =>
this.dispatch(NavigationActions.navigate({ params, routeName }));
@action
dispatch = (dispatchedAction: NavigationAction) => {
this.navigationState = rootRouter.getStateForAction(
dispatchedAction,
this.navigationState,
);
};
}
export const NavigationStore = new $NavigationStore();
@observer
class AppRouter extends React.Component<{}> {
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this._onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this._onBackPress);
}
_onBackPress = () => {
if (NavigationStore.navigationState.index === 0) {
return false;
}
NavigationStore.dispatch(NavigationActions.back());
return true;
};
render() {
return (
<RootNavigator
navigation={addNavigationHelpers({
dispatch: NavigationStore.dispatch,
state: toJS(NavigationStore.navigationState),
})}
/>
);
}
}
@rickiesmooth
Copy link

nice integration, I was wondering if you got this to work with the latest version of Mobx? Since the navigation object should now have the addEventListener field.

@AntonPuko
Copy link
Author

AntonPuko commented Apr 23, 2018

@rickiesmooth Oh..sorry, I missed your comment.
Yep, you need to handle addListener by yourself as they do that in redux-helpers...
But take a look at this:
https://github.com/Javascript-Ninja/react-navigation-mobx-helpers/
it more complete and on date version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment