How can I replace screen with React Navigation for React Native

12,727

Solution 1

Incase anyone's still figuring out how to replace screens in React Native and is using react-navigation, here it is:

import { StackActions } from '@react-navigation/native';

navigation.dispatch(
  StackActions.replace('Profile', {
    user: 'jane',
  })
);

For more information refer: https://reactnavigation.org/docs/stack-actions/#replace

Solution 2

You can use navigation.replace

Use

this.props.navigation.replace('Sc2');

Instead of

this.props.navigation.navigate('Sc2', {username: this.state.username});

You can find more from here https://reactnavigation.org/docs/en/navigation-key.html

Solution 3

Use this instead of navigation.replace

navigation.reset({
 index: 0,
 routes: [{ name: 'Profile' }],
 });

Solution 4

"Replace" is only available in stack navigation

replace typed:

import { useNavigation } from '@react-navigation/core'
import { StackNavigationProp } from '@react-navigation/stack'

type YourNavigatorParamList = {
  CurrentScreen: undefined
  DifferentScreen: { username: string }
}

const navigation = useNavigation<StackNavigationProp<YourNavigatorParamList, 'CurrentScreen'>>()

navigation.replace('DifferentScreen', { username: 'user01' })

https://reactnavigation.org/docs/navigation-prop/#navigator-dependent-functions https://reactnavigation.org/docs/typescript#annotating-usenavigation

Share:
12,727
boy_v
Author by

boy_v

Updated on June 19, 2022

Comments

  • boy_v
    boy_v almost 2 years

    How can I replace screen with React Navigation for React Native

    Now I'm a newbie I can't understand about getStateForAction now I have params on Screen 1 and Navigate to Screen 2 with passing params username with basic Navigate it's nested screen 1 > 2 on stack

    But I need to replace screen 1 with screen 2 after screen 2 it's on active (replace like ActionConst.REPLACE on router flux) and sending params on a new way

    Can someone guide me thank you.



    screen 1

      onPress = () => {
    
              this.props.navigation.navigate('Sc2', {username: this.state.username});
    
      }
    


    Screen 2

    componentWillMount() {
    
    const {state} = this.props.navigation;
    console.log(state.params.username);
    
    }
    

    ---------------

    Router

    export const LoginNavStack = StackNavigator({
      Sc1: {
        screen: Sc1
      },
      Sc2: {
       screen: Sc2,
     },
    
    });