T
TanStack8mo ago
rival-black

How to achieve a slot pattern in a Tanstack router?

#react-router, #dynamic-navbar Requirement: - I have a top navbar which renders profile dropdown which is the same across the app. - Another section of this navabar is the dynamic section. How can I control this dynamic section based on which page is rendered ? In react router v6 I have solved this problem using context and slots for dynamic content on Navbar. I will share react router code if required .
4 Replies
robust-apricot
robust-apricot8mo ago
use layout routes and the <Outlet/> component
exotic-emerald
exotic-emerald8mo ago
For the dynamic section you can use the hook useMatches and see which page is rendered, and access their loader data if you need https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook
useMatches hook | TanStack Router React Docs
The useMatches hook returns all of the objects from the router regardless of its callers position in the React component tree. [!TIP] If you only want the parent or child matches, then you can use the...
rival-black
rival-blackOP8mo ago
Do you have any example of how to inject dynamic ui to layout component when page change ?
quickest-silver
quickest-silver8mo ago
Normally if you did need to do this based on a child route, it would be something like
const isSpecificChildRoute = useMatches({
strict: false,
select: (matches) => matches.some((match) => match.id)
})

return (
<>
{isSpecificChildRoute && "your thing here"}
<Outlet />
</>
)
const isSpecificChildRoute = useMatches({
strict: false,
select: (matches) => matches.some((match) => match.id)
})

return (
<>
{isSpecificChildRoute && "your thing here"}
<Outlet />
</>
)
I think there is another property on match that is actually typesafe, but I forget which one. If you are making a layout route, and only care about the routes inside of that layout, you could also use useChildMatches which narrows the matches to only those in the outlet,

Did you find this page helpful?