How to change back button route in react navigation
Asked Answered
R

3

6

i am using react-navigation (stack-navigation). i want to change my header back button icon route.

  1. Home
  2. BookTicket
  3. MyBookings

    these are the screens i have in my project.Now when i click header back button in MyBookings screen it should route to Home Screen.

Rebekahrebekkah answered 1/9, 2017 at 6:30 Comment(2)
Have you tried using navigation.navigate([path])?Pentosan
ya i tried but didn't work for my case.but thanks for the comments.Rebekahrebekkah
T
5

There must be back button in default if your stackNavigator stack is properly configured.

But if you would like to replace the default button just add headerLeft and pass your custom component Screen Navigation Options in the page you want to change the back button handler

CreateAccountScreen.navigationOptions = ({navigation}) => ({
  headerStyle: styles.headerStyle,
  title: 'Create Account',
  headerTintColor: '#fefefe',
  headerTitleStyle: styles.headerTitleStyle,
  headerLeft: {()=>(
          <Icon name="chevron-left"
                onPress={() => navigation.goBack(null)}
                size={35} color="white"/>
       )}
});
Thoma answered 1/9, 2017 at 6:56 Comment(0)
S
4

So, the default functionality of React Navigation is:- If you press the Back Button on Mybookings screen, it will take you to previous screen i.e, BookTicket screen. To override that you could do something like this on MyBookings screen:-

import { HeaderBackButton } from 'react-navigation';
static navigationOptions = ({navigation}) => {
  return{
    headerLeft:(<HeaderBackButton onPress={()=>{navigation.navigate('Home')}}/>)
 }
}
Saponin answered 5/7, 2018 at 21:20 Comment(0)
J
3

If you don´t want to use custom back buttons (e. g. to avoid dealing with the different "native" button designs), there is also the possibility to reset the navigation state. In your case like this:

import { NavigationActions } from 'react-navigation';

const resetAction = NavigationActions.reset({
  index: 2,
  actions: [
    NavigationActions.navigate({ routeName: 'Home' }),
    NavigationActions.navigate({ routeName: 'BookTicket' }),
    NavigationActions.navigate({ routeName: 'MyBookings' }),
  ],
});
this.props.navigation.dispatch(resetAction);

This way you just set a stack of navigations and let it jump to the index position.

This setup must be done at the departing scene, so that in the next scene the back button works as expected.

But I prefer this way anyway, because it allows to maintain the default look of the header and keeps the stack clean. If you use navigation.navigate instead of navigation.back the stack becomes totally wrong for the back button.

Jeraldjeraldine answered 27/4, 2018 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.