Last active
October 19, 2023 07:05
-
-
Save badsyntax/2f73354fa7aae02571c5474297e7e06c to your computer and use it in GitHub Desktop.
React Navigation hook to check if the current (nested) route has an ancestor route.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { | |
FormsStackParamList, | |
RootStackParamList, | |
} from '@your/app'; | |
import type { | |
NavigationState, | |
ParamListBase, | |
PartialState, | |
Route, | |
} from '@react-navigation/native'; | |
import { useNavigationState } from '@react-navigation/native'; | |
type NavigationRoute< | |
ParamList extends ParamListBase, | |
RouteName extends keyof ParamList, | |
> = Route<Extract<RouteName, string>, ParamList[RouteName]> & { | |
state?: NavigationState | PartialState<NavigationState>; | |
}; | |
type ParamList = RootStackParamList & FormsStackParamList; | |
export function useHasAncestorRoute(name: keyof ParamList) { | |
const state = useNavigationState< | |
RootStackParamList, | |
NavigationState<ParamList> | |
>((_state) => _state); | |
let actualRoute = state.routes[state.index]; | |
if (actualRoute.name === name) { | |
return true; | |
} | |
while (actualRoute.state) { | |
if (actualRoute.state.index !== undefined) { | |
actualRoute = actualRoute.state.routes[ | |
actualRoute.state.index | |
] as NavigationRoute<ParamList, keyof ParamList>; | |
if (actualRoute.name === name) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment