skip to Main Content

I am currently using React Native for the first time and I am trying to render a component in a particular screen depending on the parent stack I am in as the particular screen is reused across multiple stacks.

Right now I am doing this using the following:

props?.navigation.getState()?.routes?.[0]?.name 

which is returning/having the desired effect, but I am unsure whether this is the optimal solution as I am a first-time React Native user. If multiple screens are opened, will the initial stack route always be found at

props?.navigation.getState()?.routes?.[0]?.name

2

Answers


  1. I think that for your need the getState will work just fine, but you may want to take a look at the useNavigationState as it can re-render the component when that value changes

    Login or Signup to reply.
  2. This should help you.

    const navigation = useNavigation();
    const { routes, index } = navigation.getState();
    const currentRoute = routes[index].name;
    
    • routes:- List of rendered routes.
    • index:- Index of the currently focused route.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search