Skip to content

Commit

Permalink
feat: add useIsDrawerOpen hook (facebook#299)
Browse files Browse the repository at this point in the history
  • Loading branch information
satya164 authored and osdnk committed Jan 27, 2020
1 parent 5fe140e commit ecd68af
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
6 changes: 3 additions & 3 deletions packages/core/src/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,10 @@ export type EventMapBase = Record<
{ data?: any; canPreventDefault?: boolean }
>;

export type EventMapCore = {
export type EventMapCore<State extends NavigationState> = {
focus: { data: undefined };
blur: { data: undefined };
state: { data: { state: NavigationState } };
state: { data: { state: State } };
};

export type EventArg<
Expand Down Expand Up @@ -458,7 +458,7 @@ export type NavigationProp<
* Note that this method doesn't re-render screen when the result changes. So don't use it in `render`.
*/
dangerouslyGetState(): State;
} & EventConsumer<EventMap & EventMapCore> &
} & EventConsumer<EventMap & EventMapCore<State>> &
PrivateValueStore<ParamList, RouteName, EventMap>;

export type RouteProp<
Expand Down
2 changes: 2 additions & 0 deletions packages/drawer/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export { default as DrawerContentScrollView } from './views/DrawerContentScrollV
*/
export { default as DrawerGestureContext } from './utils/DrawerGestureContext';

export { default as useIsDrawerOpen } from './utils/useIsDrawerOpen';

/**
* Types
*/
Expand Down
32 changes: 32 additions & 0 deletions packages/drawer/src/utils/useIsDrawerOpen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import * as React from 'react';
import { useNavigation, ParamListBase } from '@react-navigation/native';
import { DrawerNavigationProp } from '../types';

/**
* Hook to detect if the drawer is open in a parent navigator.
*/
export default function useIsDrawerOpen() {
const navigation = useNavigation();

let drawer = navigation as DrawerNavigationProp<ParamListBase>;

// The screen might be inside another navigator such as stack nested in drawer
// We need to find the closest drawer navigator and add the listener there
while (drawer && drawer.dangerouslyGetState().type !== 'drawer') {
drawer = drawer.dangerouslyGetParent();
}

const [isDrawerOpen, setIsDrawerOpen] = React.useState(() =>
drawer ? drawer.dangerouslyGetState().isDrawerOpen : false
);

React.useEffect(() => {
const unsubscribe = drawer.addListener('state', e => {
setIsDrawerOpen(e.data.state.isDrawerOpen);
});

return unsubscribe;
}, [drawer]);

return isDrawerOpen;
}

0 comments on commit ecd68af

Please sign in to comment.