useHasAncestorRoute.ts
This file contains 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; | |
} |