Roman Levytskyy
Roman Levytskyy

Reputation: 11

Have a stack navigator always render initialRoute

I'm building a react native app and I'm using react-navigation package. I have a tab navigator for the app and each tab has a stack navigator in it. Something like this:

const HomeStack = StackNavigation({
    Info: {screen: Info},
    Main: {screen: Main}
})

const SearchStack = StackNavigation({
    Search: {screen: Search},
    SearchResult: {screen: SearchResult}
})

TabNavigation({
  Home: {screen: HomeStack},
  Search: {screen: SearchStack}
})

So let's say I did a search and I'm now on SearchResult screen. I then go back to Home screen by pressing home tab. Now when I go back to search tab it shows me the SearchResult screen. Is there a way to force react-navigation to always render a Search screen when you go to it from the Tab?

I made a project on snack to illustrate this https://snack.expo.io/rkMzWoh17

Upvotes: 1

Views: 1028

Answers (2)

anfo000
anfo000

Reputation: 1

You can use something like this inside every stack screen.

   const Search = ({ navigation }) => {
      useLayoutEffect(() => {
          const blur = navigation.addListener('blur', () => {
            navigation.popToTop();
          });
      }, []);
   }

This pops the stack to the initial screen everytime you navigate away.

More information here: https://reactnavigation.org/docs/navigation-events

Upvotes: 0

Nahid Hasan
Nahid Hasan

Reputation: 707

use initial route name like this in searchstack navigation like this

 {
    initialRouteName: 'Search',
  }

Upvotes: 1

Related Questions