T
TanStack14mo ago
curious-teal

Accessing Path Params For Component in createRoute

Lets say i have a general component that accepts a prop called id, how would I pass that id to my component without having to define route functions inside my component. I'm wondering if something like this is possible:
const Route = createFileRoute('/posts/$postId')({
component: () => <PostComponent id={id} />
})
const Route = createFileRoute('/posts/$postId')({
component: () => <PostComponent id={id} />
})
2 Replies
other-emerald
other-emerald14mo ago
That wouldn't be possible since the components are not passed any props. You can however use the useParams hook with the from field to get this value. https://tanstack.com/router/latest/docs/framework/react/api/router/useParamsHook Or you can also, use the getRouteApi helper to get access to all the hooks for a route. https://tanstack.com/router/latest/docs/framework/react/api/router/getRouteApiFunction
useParams hook | TanStack Router React Docs
The useParams method returns all of the path parameters that were parsed for the closest match and all of its parent matches. useParams options
getRouteApi function | TanStack Router React Docs
The getRouteApi function provides type-safe version of common hooks like useParams, useSearch, useRouteContext, useNavigate, useLoaderData, and useLoaderDeps that are pre-bound to a specific route ID and corresponding registered route types. getRouteApi options
curious-teal
curious-tealOP14mo ago
I see i see, thanks! I was thinking more of being able to pass a generalized component thats not dependent on routes to the component field, however looks like ill just need to pass a layout component and then the generalized component within that.

Did you find this page helpful?