react-nativeexponavigation-drawerreact-navigation-drawer

Accessing DrawerStatus From Sibling Component


My main app contains a NavigationContainer with a Drawer.Navigator that houses its Drawer.Screen components.

Outside of the Navigator, I have a floating action button component within the NavigationContainer that I'd like to conditionally render based on if the navigation drawer is open.

const Drawer = createDrawerNavigator()

export default function App() {
    return (
        <NavigationContainer ...>
          
          <Drawer.Navigator ...>
            <Drawer.Screen ... />
            <Drawer.Screen ... />
            <Drawer.Screen ... />
           
          </Drawer.Navigator>
          
          <FloatingActionButton />
           
        </NavigationContainer>
      )
    }
}

Since I can't use useDrawerStatus within the FloatingActionButton component because the component isn't a child of Drawer.Navigator (which can't house the button itself, because Navigator can only contain Screen, Group, and Fragment components), how can I listen to the drawer status or otherwise access its current open state?


Solution

  • Use screenListeners prop to listen to state event and check if drawer is present. Something like this:

    export default function App() {
      const [isDrawerOpen, setIsDrawerOpen] = useState(false)
    
      return (
        <NavigationContainer>
          <Drawer.Navigator 
            screenListeners={{
              state: (e) => {
                setIsDrawerOpen(e.data.state.history.some((it) => it.type === 'drawer'))
              }
            }}>
    ...
          </Drawer.Navigator>
          {!isDrawerOpen && <FloatingActionButton/>}
        </NavigationContainer>
      )
    }