T
TanStack3y ago
wise-white

Getting breadcrumbs

Hi I am new to this library, I want to display breadcrumbs in my app in a component. On my route /projects/$projectID I want to get the array ["projects", "theID"] so I can render the breadcrumbs. What is the best approach for this? I've been looking at useRouter and useMatches but they give me a lot of information I do not need and I need to do a lot of manipulation to the output of this. I was looking into this: https://tanstack.com/router/v1/docs/guide/router-context#processing-accumulated-route-context but routeContext is missing for all the matches, what am I doing wrong?
Router Context | TanStack Router Docs
TanStack Router's router context is a very powerful tool that can be used for dependency injection among many other things. Aptly named, the router context is passed through the router and down through each matching route. At each route in the hierarchy, the context can be modified or added to. Here's a few ways you might use the router context...
5 Replies
wise-white
wise-whiteOP3y ago
I'm currently working around my issue by just rendering the breadcrumbs within the component in the routes. But now for handling active states in my navbar, which is renderd way higher in the component tree I find myself writing code like this:
const matches = useMatches();

const onProjectRoute = matches?.[1]?.routeId === "/projects";
const selectedProject = matches?.[2]?.params?.projectName;
const matches = useMatches();

const onProjectRoute = matches?.[1]?.routeId === "/projects";
const selectedProject = matches?.[2]?.params?.projectName;
Is this the intended way to reach information like this? Or is there some hook or interface which I am missing completely? @Tanner Linsley sorry for the ping, but could you explain what is the best way to get information like this 🙂 ? I feel like I sometimes want to know where I am within my routing tree from higher up in the component tree, like for example the navbar.
fair-rose
fair-rose3y ago
useMatches() or router.state.matches will give you this info You can useRouterState() with a select option to only listen to matches From there you can get match info and route info for each match. Including loader data, route meta, etc
wise-white
wise-whiteOP3y ago
thanks for your reply! 🙏 Sounds like I am doing it correctly then and should just write some helper functions to parse the matches array 🙂
fair-rose
fair-rose3y ago
Yep! Usually it’s just filtering out matches that don’t have the data you want. Them mapping them to a breadcrumb component. It just some links joined together with reduce
wise-white
wise-whiteOP3y ago
❤️

Did you find this page helpful?