Is there - a drawer-equivalent to the property tabPress react-navigation

Viewed 60

I want to execute a certain code whenever a drawer element is clicked. In other words, I am looking for a drawer equivalent to the property tabPress. I tried adding my callback to the property focus. However, this callback is executed whenever "any screen" in the relevant stack is "in focus."

I want the code to be exuted only if the user "clicks" on a "drawer item". Is this at all possible?

import { createDrawerNavigator } from "@react-navigation/drawer";
const MyNav = createDrawerNavigator();

<MyNav.Navigator> 
  <MyNav.Screen name="abc" component={abcStack} 
    listeners={ ({ navigation, route }) => ({
        // This is executed whenever any screen in the stack is accessed. This does NOT satisfy my requirements. 
        focus: (e) => {
          console.log("We are in focus"); 
        }, 
        
        // Is there something like "tabPress" for Drawer stacks? 
        tabPress: (e) => {
          console.log("We are on tabPress"); 
        }, 
    })} 
  />
</MyNav.Navigator>

This question is related to React-Navigation Version 6.

1 Answers

I found a workaround, which should work in many cases. The idea is to send a parameter to the screen, which the drawer is calling, whenever the drawer is clicked. If the drawer calls a stack, you would have to add the parameter to the 1st screen of the stack

Drawer navigation with a single screen:

import { createDrawerNavigator } from "@react-navigation/drawer";
const MyNav = createDrawerNavigator();

<MyNav.Navigator> 
    <MyNav.Screen name="screen1" component={screen1} initialParams={{ opParam: "abc" }}/>
</MyNav.Navigator> 

Drawer navigation with a stack:

import { createDrawerNavigator } from "@react-navigation/drawer";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

const stack1 = () => {
    const MyStack = createNativeStackNavigator();
    return (
    <MyStack.Navigator>
        <MyStack.Screen name="screen1" component={screen1}/>
    </MyStack.Navigator>
    );
}; 

const MyNav = createDrawerNavigator();

<MyNav.Navigator> 
    <MyNav.Screen name="stack1" component={stack1}/>
</MyNav.Navigator> 

Screen 1:

import React, { useEffect } from "react";
import { useIsFocused } from "@react-navigation/native";

const screen1 = (props) => {
 const isFocused = useIsFocused();

 useEffect(() => {      
    async function fetchData() {        
        // If this screen was loaded because of a click on the drawer, the following condition would be true.
        if (props.route?.params?.opParam === "abc") {
            // do whatever you want done when the user clicks on the drawer... 
            console.log("drawer was clicked"); 
        } 
    }
    
    // Only if this screen is in focus, we execute the function above.
    if (isFocused) {
        fetchData();
    }
 }, [ isFocused, props.route?.params?.opParam, ]); 

 return(
   // ............
 );
}; 
Related