UI/UX has both high hanging and low hanging fruits, and this is certainly one of the more low hanging ones to enhance the experience. A main navigation, be it a navbar or a navigation tree on either side, that indicates where in it the user is currently browsing is one of the more basic things. This is perhaps also the oldest UX tool the web has, dating back to the first HTML pages and browsers in the 90's.
TanStack Router, liked for its typesafe approach that borrows lots of ideas from Vue/Angular routers, offers a smooth solution to this UI necessity through the activeProps
attribute of its Link
element. This attribute allows developers to apply specific styles to active links, enhancing the navigation experience. Let's delve into a practical example to see activeProps
in action.
Constructing the Navigation Component
In our scenario, we'll construct a MainNav
component to render a navigation menu with two items: Dashboard and Messages.
import { dashboardRoute, threadsRoute } from '@/Router'
import { Link } from '@tanstack/react-router'
export function MainNav() {
const menuItems = [
{ name: 'Dashboard', path: dashboardRoute.fullPath },
{ name: 'Messages', path: messagesRoute.fullPath },
]
return (
<nav className='hidden md:flex items-center space-x-4 lg:space-x-6 mx-4 text-gray-500'>
{menuItems.map((item) => {
return (
<Link
key={item.name}
to={item.path}
className='text-sm font-medium transition-colors hover:text-black'
activeProps={{ className: 'text-black' }}
>
{item.name}
</Link>
)
})}
</nav>
)
}
Here’s a breakdown of the key parts in the code snippet above:
- We defined a
MainNav
function component. - We created an array
menuItems
to store our navigation items, where each item has a name and a path. - Within the
nav
element, we iterated overmenuItems
to generateLink
elements for each navigation item. - For each
Link
element, we applied common styling via theclassName
attribute and used theactiveProps
attribute to specify the styling for active links. When a link is active, thetext-black
class is applied, changing its text color to black.
The activeProps
attribute offers a neat and intuitive way to style active links, improving user orientation and the overall user experience. The use of activeProps
in TanStack Router's Link
element demonstrates a practical solution for achieving a polished, user-friendly navigation system.
For further insights and use-cases, refer to the official TanStack documentation on Navigation.
Top comments (1)
I am not sure this works anymore, but I kinda like the idea. It's too bad there are not examples of how to generate a nav based on your routes. Then again, it seems like its silly to have to manually build your nav. It's too easy to forget to add a link to your array of objects and you have to maintain in two places. There should be an easier way to do this.