Getting the active path: Best Practices
I've just started using the router, love it! Feels much nicer to use than react-router-dom v6 as a Typescript user.
One question is the best way to do this very simple pattern. Heres some psuedo code
What is the best way to apply the "selected" styling based on what route is active (the aboutRoute, or the profileRoute)
Doing some searching, I could use useRouter().state and pick out the path from the location (or the window api of course). But in what is a very normal use case, I felt kinda like I was taking an escape-hatch route by using useRouter (and getting access to the very large and powerful router object). So I wasn't sure if there was a more "tanstacky" way/hook to use, similar to useLocation() in react-router-dom v6
3 Replies
sunny-green•2y ago
Link supports this already via activeProps.
checkout this example
https://github.com/TanStack/router/blob/beta/examples%2Freact%2Fkitchen-sink%2Fsrc%2Fmain.tsx#L158GitHub
router/examples/react/kitchen-sink/src/main.tsx at beta · TanStack/...
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering. - TanStack/router
dependent-tanOP•2y ago
Works perfectly, thank you 🙂
I also needed to know the state outside of the Link but was able to easily keep track by storing it in state using Link's onClick. (Just mentioning in case anyone else needs the use case)
like-gold•2y ago
Tracking the state based on click may not work if you refresh the page.
Better approach is to match the route with location. You can doing something like this.