TanStackT
TanStack4mo ago
9 replies
yucky-gold

What is the cleanest way to pass route parameters to component files?

I couldn't find a clear-cut example within the documentation on how you handle it when your components live in components files and your routes live under the routes path. I want to use things like use params but I don't know how to get to them without using it directly within the route file. I've thought of two ways to do it and I'm not sure which one's better. Let me know which one is the preferred pattern if there is one.

Pattern 1

Determine params in the Route file and pass as props to component.
export const Route = createFileRoute("/projects_/$projectId")({
  component: RouteComponent,
});

function RouteComponent() {
  const { projectId } = Route.useParams();
  const { tab } = Route.useSearch();

  return (
    <Project
      projectId={projectId}
      activeTab={tab}
    />
  );
}


Pattern 2

Use the
from
parameter in global useParams within component file:
//src/routes/projects_/$projectId.jsx
export const Route = createFileRoute("/projects_/$projectId")({
  component: RouteComponent,
});

function RouteComponent() {
  return (
    <Project />
  );
}


//src/components/Project.jsx
import { useSearch, useParams } from "@tanstack/react-router";

function Project() {
    const {projectId} = useParams({from: "/projects_/$projectId"})
    ...
}

Pattern 3

Use the getRouteApi function.
//src/routes/projects_/$projectId.jsx
export const Route = createFileRoute("/projects_/$projectId")({
  component: RouteComponent,
});

function RouteComponent() {
  return (
    <Project />
  );
}


//src/components/Project.jsx
import { getRouteApi } from '@tanstack/react-router'

const route = getRouteApi("/projects_/$projectId")

function Project() {
  const {projectId} = route.useParams()

  return <div>...</div>
}
Was this page helpful?