Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Last active October 19, 2023 07:05
Show Gist options
  • Save badsyntax/2f73354fa7aae02571c5474297e7e06c to your computer and use it in GitHub Desktop.
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.
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