Search code examples
reactjsreact-nativereact-navigationreact-navigation-stackreact-navigation-v5

@react-navigation/native and @react-navigation/stack read whole stack


OK, so I have my App.js

<NavigationContainer>
  <Stack.Navigator initialRouteName="Home">
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Main" component={MainScreen} />
    <Stack.Screen name="Login" component={LoginScreen} />
    <Stack.Screen name="Pokus" component={PokusScreen} />
  </Stack.Navigator>
</NavigationContainer>;

Then in my Home component, I redirect to the Main component.

I pass navigation like this:

export default function Home({ navigation })

My question is: Can I now read stack?

Can I say something like: navigation.ReadStack()?

What I want to see?:I want to see something like { { name: "Home", index: 0 }, { name: "Main", index: 1 } }

Is this possible?

Thanks for any help!

EDIT: My code in Main component

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { last_activity_token, UpdateActivity } from '../Models/activityModel';
import {useNavigationState} from '@react-navigation/native';

export default function Main({ navigation }) {
  //constanty -- constants
  const [activity, setActivity] = useState(new last_activity_token());

  const Pokus = () => {
    const state = useNavigationState(state => state);
    alert(JSON.stringify(state.routes))
  }

  //Load event
  React.useEffect(() => {
    activity.page.name = "Main";
    UpdateActivity(activity);
  });

  //vzhled stránky -- design of page 
  return (
      <View style={styles.layout}>
        <Text>Main</Text>
        <View style={styles.MainContent}>
          <Text>Tady se to vše bude odehrávat</Text>
          <Button onPress={Pokus}/>
        </View>
      </View>
    );
}

//css
const styles = StyleSheet.create({
    layout: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
    MainContent: {
      marginTop: 20
    }
});

Solution

  • You can get the current state by using the useNavigationState hook like below

    https://reactnavigation.org/docs/use-navigation-state/

    import {useNavigationState} from '@react-navigation/native';
    
    const state = useNavigationState((state) => state);
    
    alert(JSON.stringify(state.routes));
    

    This will give an output of the screen in the route