TanStackT
TanStack10mo ago
10 replies
full-green

Best way to detect pathless routes?

I have a sort of a 2d navigation in my app, and have an idea to use pathless layout routes to detect where we are in the "matrix". See attached image, from this file structure I want to detect:
- level (root, retailer, machine)
- category (commercial, logistics, operational)

What is the best way to do this? I have two ways that work now:
1. Use the useMatches() hook, check for string "/_commercial"
2. Use router context and store level and category here

Some example code:
export function useMatrixCategory(): Category | undefined {
const allMatchedRouteIds = useMatches().map((c) => c.routeId.toString());
allMatchedRouteIds.forEach((routeId) => {
if (routeId.indexOf('/_operational') !== -1) {
return 'operational';
} else if (routeId.indexOf('/_commercial') !== -1) {
return 'commercial';
} else if (routeId.indexOf('/_logistics') !== -1) {
return 'logistics';
}
return undefined;
});

// Alternative: put in context
/* const router = useRouter();
const context = router.options.context;
console.log('useMatrixCategory', context.category);
return context.category; */
}

Are there any other tools I can use? Better type support?
image.png
Was this page helpful?