Skip to content

Instantly share code, notes, and snippets.

@uqmessias
Last active October 20, 2017 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uqmessias/29e064c014d7b997a0a0a47f5618d088 to your computer and use it in GitHub Desktop.
Save uqmessias/29e064c014d7b997a0a0a47f5618d088 to your computer and use it in GitHub Desktop.
Function to replace route in a state with another route by routeName property
const replaceAtRouteName = (state, routeName, route) => {
if (!route || !routeName || !state.routes) {
return state
}
const newState = { ...state }
let replaced = false
state.routes.forEach((value, index) => {
let replacedRoute = value
if (value.routeName === routeName) {
replacedRoute = route
} else if (value.routes) {
const newRoute = replaceAtRouteName(value, routeName, route)
if (newRoute !== value) {
replacedRoute = newRoute
}
}
if (replacedRoute !== value) {
const routes = newState.routes.slice()
routes[index] = replacedRoute
newState.routes = routes
replaced = true
}
})
if (replaced) {
return newState
}
return state
}
const defaultGetStateForAction = HomeNavigator.router.getStateForAction
const getKey = () => `route-key-${Date.now()}`
const navigationOptions = { navigationOptions: { header: null } }
const configsWithSlieTransisions = {/* boiler plate */}
const configsWithFadeInOutTransisions = {/* boiler plate */}
const configsWithModalTransisions = {/* boiler plate */}
const LoginNavigator = StackNavigator(
{
[RouteNames.LOGIN_FIRST_STEP]: {
...navigationOptions,
screen: LoginFirstStep,
},
[RouteNames.LOGIN_SECOND_STEP]: {
...navigationOptions,
screen: LoginSecondtStep,
},
},
configsWithSlieTransisions,
)
const ScreenNavigator = StackNavigator(
{
[RouteNames.LOGIN_NAVIGATION]: {
...navigationOptions,
screen: LoginNavigator,
},
[RouteNames.HOME]: {
...navigationOptions,
screen: Home,
},
},
configsWithFadeInOutTransisions,
)
const HomeNavigator = StackNavigator(
{
ScreenNavigation: {
...navigationOptions,
screen: ScreenNavigator,
},
[RouteNames.TOUR]: {
...navigationOptions,
screen: Tour,
},
[RouteNames.SCREEN_AFTER_TOUR]: {
...navigationOptions,
screen: AfterTour,
},
},
configsWithModalTransisions,
)
HomeNavigator.router.getStateForAction = (action, state) => {
if (state && action && action.type === 'YourActionTypeToReplaceRoutes') {
return replaceAtRouteName(state, action.routeNameReplaced, {
key: getKey(),
routeName: action.routeNameToReplace,
})
}
return defaultGetStateForAction(action, state)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment