T
TanStack13mo ago
rising-crimson

Recommended Path Segment

Lets say I have the following routes - hello - hello/foo - hello/bar - hello/fee In the hello component I need to get the last path segment: [undefined] | foo | bar | fee (undefined is for the first route). Is there a recommended way to do this ? Is the following the recommended way?:
const pathname= useLocation({select: (location) => location.pathname})
const lastSegment = pathname.slice(pathname.lastIndexOf('/'))
const pathname= useLocation({select: (location) => location.pathname})
const lastSegment = pathname.slice(pathname.lastIndexOf('/'))
I was wondering if there was something like:
const matchRoute = useMatchRoute()
const params = matchRoute({to: 'hello/:lastsegment'})
const matchRoute = useMatchRoute()
const params = matchRoute({to: 'hello/:lastsegment'})
Note: I have a typescript tag on this post because matchRoute's to doesn't like hello/$lastsegment since a path parameter route doesnt exist (hello/$lastSegment).
2 Replies
quickest-silver
quickest-silver13mo ago
StackBlitz
Router Quickstart File Based Example (forked) - StackBlitz
Run official live example code for Router Quickstart File Based, created by Tanstack on StackBlitz
quickest-silver
quickest-silver13mo ago
import {
createFileRoute,
Outlet,
useChildMatches,
useRouter,
} from '@tanstack/react-router';

export const Route = createFileRoute('/hello')({
component: () => {
const m = useChildMatches();
const router = useRouter();
const value = router.routesByPath[m[0].fullPath]?.path;
return (
<>
<div>This is the child: {value}</div>
<Outlet />
</>
);
},
});
import {
createFileRoute,
Outlet,
useChildMatches,
useRouter,
} from '@tanstack/react-router';

export const Route = createFileRoute('/hello')({
component: () => {
const m = useChildMatches();
const router = useRouter();
const value = router.routesByPath[m[0].fullPath]?.path;
return (
<>
<div>This is the child: {value}</div>
<Outlet />
</>
);
},
});

Did you find this page helpful?