Skip to content

Instantly share code, notes, and snippets.

@jtibbertsma
Last active December 28, 2020 06:23
Show Gist options
  • Save jtibbertsma/5fc91cca8c61dfdf79126d137ff624b1 to your computer and use it in GitHub Desktop.
Save jtibbertsma/5fc91cca8c61dfdf79126d137ff624b1 to your computer and use it in GitHub Desktop.
react-native-navigation redux middleware example
import { createAction } from 'redux-actions';
import {
NAVIGATION_PUSH,
NAVIGATION_POP,
NAVIGATION_RESET_TO,
NAVIGATION_POP_TO_ROOT
} from './actions';
export const push = createAction(NAVIGATION_PUSH);
export const pop = createAction(NAVIGATION_POP);
export const resetTo = createAction(NAVIGATION_RESET_TO);
export const popToRoot = createAction(NAVIGATION_POP_TO_ROOT);
import {
NAVIGATION_PUSH,
NAVIGATION_POP,
NAVIGATION_RESET_TO,
NAVIGATION_POP_TO_ROOT
} from './actions';
let currentNavigator = null;
export function setNavigator(navigator) {
currentNavigator = navigator;
}
function push(action) {
currentNavigator.push(action.payload);
}
function pop(action) {
currentNavigator.pop(action.payload);
}
function resetTo(action) {
currentNavigator.resetTo(action.payload);
}
function popToRoot() {
currentNavigator.popToRoot();
}
export default function navigationMiddleware(store) {
return next => action => {
switch (action.type) {
case NAVIGATION_PUSH:
push(action);
break;
case NAVIGATION_POP:
pop(action);
break;
case NAVIGATION_RESET_TO:
resetTo(action);
break;
case NAVIGATION_POP_TO_ROOT:
popToRoot();
break;
}
next(action);
}
}
import React, { Component } from 'react';
import hoistStatics from 'hoist-non-react-statics';
import { setNavigator } from './navigation';
import getDisplayName from './getDisplayName'; // Copied from react-redux source
/**
* This HOC is meant to decorate any screen component that is at the
* root of the navigation stack. It uses its constructor to set the global
* navigation object. Having a global navigation object that lives in a
* redux middleware allows us to control navigation by dispatching redux
* actions.
*/
export default function rootScreen(WrappedComponent) {
class RootScreen extends Component {
constructor(props) {
super(props);
const { navigator } = props;
setNavigator(navigator);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
const hoisted = hoistStatics(RootScreen, WrappedComponent);
hoisted.displayName = 'RootScreen(' + getDisplayName(WrappedComponent) + ')';
return hoisted;
}
import { Navigation } from 'react-native-navigation';
import SomeScreen from './SomeScreen';
import rootScreen from './rootScreen';
export function registerScreens(store, Provider) {
Navigation.registerComponent(
'prefix.SomeScreen',
() => rootScreen(SomeScreen),
store,
Provider
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment