How to navigate to two screens in a sibling navigator?

Viewed 531

I have a navigator setup as this: (using react-navigation 5.x)

<BottomTabNavigator>
  <DashboardNavigator>
    <MainScreen />
  </DashboardNavigator>
  <ItemNavigator>
    <ItemListScreen />
    <ItemDetailScreen />
  </ItemNavigator>
</BottomTabNavigator>

I want to go from MainScreen to ItemDetailScreen, but I want the header back button lead to ItemListScreen. In other words, I want MainScreen to be replaced by a stack with [ItemListScreen, ItemDetailScreen].

I tried using

navigation.navigate(
  'ItemNavigator',
  {
    screen: 'ItemListScreen',
    params: {
      screen: 'ItemDetailScreen',
      params: {id: itemId}
    }
  }
)

but that only gets me to ItemListScreen without ItemDetailScreen. How do I do this? Restart also didn't help

2 Answers

You want to use CommonActions

Here is the code for posterity:

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

navigation.dispatch(
  CommonActions.reset({
    index: 1,
    routes: [
      { name: 'Home' },
      {
        name: 'Profile',
        params: { user: 'jane' },
      },
    ],
  })
);

In your case, simply replace Home with ItemListScreen and Profile with ItemDetailScreen.

I Can Provide You With a More Efficient Way which is called react-native-navigation if you want to Navigate Between Two Screens Then Here Is The Code

class App extends Component {
  constructor(props) {
    super(props);
    //Setting Up The States
    var data;
    this.state = {
      page: 'home',
      data: {},
    };
  }

  //render method
  render() {
    //return method
    return (
     <NavigationContainer>
     <Stack.Navigator>
        <Stack.Screen name="Screen1" component={Screen}/>
        <Stack.Screen name="Screen2" component={Screen2}/>
     </Stack.Navigator> 
     </NavigationContainer>
    );
  }
}

This Is The Screen Component

const Screen = ({ navigator, router }) => (
   <Text>This Is Screen 1</Text>
   <Button title="Go To Screen 2" onPress={() => {
    navigator.push('Screen2')
   }}/>
)

This Is The Screen 2 Component

const Screen2 = ({ navigator, router }) => (
   <Text>This Is Screen 2</Text>
   <Button title="Go To Screen 1" onPress={() => {
    navigator.pop()
   }}/>
)

and this is the link To React Native Navigation

Related