lucassp
lucassp

Reputation: 4167

react-navigation 5 navigate multiple routes at once

Is there a better way of navigating multiple routes than the following one?

   NavigatorService.navigate('Screen1', params);
   NavigatorService.navigate('Screen2', params);

Where Screen1 and Screen2 are Siblings in the same stack navigator.

Upvotes: 3

Views: 4167

Answers (2)

lucassp
lucassp

Reputation: 4167

I found a way to do it and also preserve the current stack:

navigator.dispatch((state) => {
    const newRoutes = [...state.routes, ...routesToAdd];
    
    return CommonActions.reset({
        ...state,
        routes: newRoutes,
        index: newRoutes.length - 1,
    });
});

Upvotes: 3

Wen W
Wen W

Reputation: 2647

Here's a quick example I created on snack. Basically, you can create an array of screens, and use the reset function to create the history.

navigation.dispatch(
            CommonActions.reset({
              index: 4,
              routes: [
                {
                  name: 'Stack',
                  params: { screen: 'StackView1' },
                },
                {
                  name: 'Stack',
                  params: { screen: 'StackView2' },
                },
                {
                  name: 'Stack1',
                  params: { screen: 'Stack1View1' },
                },
                {
                  name: 'Stack1',
                  params: { screen: 'Stack1View2' },
                },
                {
                  name: 'Stack1',
                  params: { screen: 'Stack1View3' },
                },
              ],
            })
          );

Upvotes: 5

Related Questions