Quantcast
Channel: Recent Gists from badsyntax
Viewing all articles
Browse latest Browse all 31

React Navigation hook to check if the current (nested) route has an ancestor route.

$
0
0
useHasAncestorRoute.ts
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;
}

Viewing all articles
Browse latest Browse all 31

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>