Navigate to another screen using react-navigation

Viewed 228

I am using to route to another screen using the method mentioned on this link. The problem is that they are using hooks inside a functional component. And I am using a class component.

My problem is, how can I use this navigation to navigate from one screen to another inside a child component which is a class component.

Because class components wont allow me to use hooks inside it.

My routes are as Follows:

const Tab = createBottomTabNavigator();
const Stack = createStackNavigator();

const HomeScreenRoutes = () => {
    return (
        <Tab.Navigator>
            <Tab.Screen
                name="Dashboard"
                component={DashboardScreen}/>
            <Tab.Screen
                name="Transactions"
                component={TransactionsScreen}/>
            <Tab.Screen
                name="Reports"
                component={ReportsScreen}/>
            <Tab.Screen
                name="About Me"
                component={UserInfoScreen}/>
        </Tab.Navigator>

    );
};

const Routes = () => {
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen
                    name="LoginSignup"
                    component={AuthenticationScreen}
                    options={
                        {title: 'Login or Signup', headerShown: false}
                    }/>
                <Stack.Screen
                    name="HomeScreen"
                    component={HomeScreenRoutes}
                    />
            </Stack.Navigator>
        </NavigationContainer>
    );
};
1 Answers

From the components passed in as props to <Stack.Screen> you can easily access the navigation prop. This value is the same as you'd get from the useNavigation hook.

class DashboardScreen extends React.Component {
  render() {
    const navigation = props.navigation; // this should be populated
    // you can use this in a component to navigate from there.
  }
}

If you want access to navigation from a nested component(ie- child of a child) you will have to pass that along as a prop down the heirachy.

Related