How can I replace screen with React Navigation for React Native

Viewed 21441

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,
 },

});
4 Answers

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

Use this instead of navigation.replace

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

"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

Related