-
I am currently defining a default context when creating the router, but I have no way to access it through the component. What I have to do is use the loader function, and then use the hook useLoaderData inside the component. It is very cumbersome to do and repetitive and I would like that through the arguments passed to the component function I get the context instead of doing all those steps above each time and so I also avoid using unnecessary hooks. const router = createRouter({
// eslint-disable-next-line react/prop-types
Wrap: ({ children }) => {
return <ConfigProvider theme={{ cssVar: true }}>{children}</ConfigProvider>;
},
context: {
theme: theme.getDesignToken({ cssVar: true }),
},
routeTree,
}); export const Route = createRootRouteWithContext<{ theme: AliasToken }>()({
component: Root,
});
export function Root() {
return (
<>
<Outlet />
<TanStackRouterDevtools />
</>
);
} // Current solution
export const Route = createFileRoute('/')({
component: () => {
return (
<>
<HomePage />
</>
);
},
loader: ({ context }) => {
return {
...context,
};
},
});
export function HomePage() {
const x = Route.useLoaderData();
return (
<div>
<h3>Welcome Home! {x.theme.blue}</h3>
</div>
);
}
// Better solution
export const Route = createFileRoute('/')({
component: () => {
return (
<>
<HomePage />
</>
);
}
});
export function HomePage({ context: x }) {
return (
<div>
<h3>Welcome Home! {x.theme.blue}</h3>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
It's available on matches, so useRouterState or useMatches should give you the context for each match: |
Beta Was this translation helpful? Give feedback.
-
It's not working: |
Beta Was this translation helpful? Give feedback.
-
I see that with useMatches it comes in the loaderData property, but as I mentioned, isn't there a way to do it without hooks? Let the component that renders the path receive that as props. |
Beta Was this translation helpful? Give feedback.
components that render on a route don't receive any props. You get loader data with
useLoaderData()
. You get path params withuseParams()
. And you can get context withuseMatches()
and then access.context
. It's even shown in your image ...