Updated April 24, 2017

Replace a Screen Using React Navigation

Originally publish on medium.com.

0

One challenge I faced while migrating to React Navigation was how to replace a screen when using React Navigation. Right now there’s no built in way to do it (though that should change soon-ish) but it’s still possible!

In this short video I cover how you can do it.

Enjoy the video? Subscribe!

Code

routes.js

const prevGetStateForActionHomeStack = HomeStack.router.getStateForAction;
HomeStack.router.getStateForAction = (action, state) => {
    if (state && action.type === 'ReplaceCurrentScreen') {
      const routes = state.routes.slice(0, state.routes.length - 1);
      routes.push(action);
      return {
        ...state,
        routes,
        index: routes.length - 1,
      };
    }
    return prevGetStateForActionHomeStack(action, state);
  },
};

NearMe.js

replaceScreen = () => {
  const { locations, position } = this.props.navigation.state.params;
  this.props.navigation.dispatch({
    key: 'NearMeMap',
    type: 'ReplaceCurrentScreen',
    routeName: 'NearMeMap',
    params: { locations, position },
  });
};

NearMeMap.js

replaceScreen = () => {
  const { locations, position } = this.props.navigation.state.params;
  this.props.navigation.dispatch({
    key: 'NearMe',
    type: 'ReplaceCurrentScreen',
    routeName: 'NearMe',
    params: { locations, position },
  });
};
React Native School Logo

React Native School

Want to further level up as a React Native developer? Join React Native School! You'll get access to all of our courses and our private Slack community.

Learn More