Why useNavigation hook doesn't work in custom side bar?

534 views Asked by At

If I create custom drawer:

<DrawerStack.Navigator
      drawerContent={props => <SideMenu {...props} />}>

It requires to pass props in order to get navigation object inside it.
And if I have following:

<ClientsStack.Navigator>
      <ClientsStack.Screen name="Clients" component={ClientsScreen} />
      <ClientsStack.Screen
        name="ClientDetails"
        component={ClientDetailsScreen}
      />
    </ClientsStack.Navigator>

And inside ClientsScreen I have FlatList which has:

renderItem={({ item }) => <ClientCard id={item.id} />}

inside ClientCard component which is not screen it's just dummy component
I can use useNavigation hook there.
Why it can be used there but not in custom drawer component?

1

There are 1 answers

4
Thibault Capelli On BEST ANSWER

You can't use useNavigation inside your drawerContent cause the hook is only available from your screens and their childs.

At the origin the only way to get navigation was to pass it from your screen to their childs. But since the useContext hook exist, the library provides a useNavigation to easily get the navigation in deep nested components. (and simplify the code a lot)

A drawer custom component is not a screen or wrapped into a screen. So there is just no reason to get the navigation from it with useNavigation. And I easily guess there is no usecase where we have deep nested components inside it cause it is usually just a menu.