CORE CONCEPTS
Define Active Links
Active links are links that are highlighted when the current route matches the link's to property.
Without extra tools, you can define active links manually by combining useLocation and Link components.
import React from "react"; import { Link, useLocation } from "rasengan"; type Props = { to: string; children: React.ReactNode; }; export default function ActiveLink({ to, children }: Props) { const { pathname } = useLocation(); return ( <Link to={to} className={`${pathname === to ? "active" : ""}`}> {children} </Link> ); }
NavLink Component
Rasengan.js provides a NavLink component that makes it easier to define active links.
import React from "react"; import { NavLink } from "rasengan"; type Props = { to: string; children: React.ReactNode; }; export default function ActiveLink({ to, children }: Props) { return ( <NavLink to={to} className={({ isActive, isPending }) => isPending ? "pending" : isActive ? "active" : "" } > {children} </NavLink> ); }
Note: Active state
The NavLink component becomes active when the current route start with the to prop value.
When to="/docs" Current route: /docs => isActive: true Current route: /docs/getting-started/introduction => isActive: true Current route: /packages => isActive: false Current route: /blog => isActive: false
Props
children
Can be regular React children or a function that receives an object with the active and pending states of the link.
<NavLink to="/tasks"> {({ isActive }) => ( <span className={isActive ? "active" : ""}>Tasks</span> )} </NavLink>
end
Changes the matching logic for the active and pending states to only match to the "end" of the NavLinkProps.to. If the URL is longer, it will no longer be considered active.
Learn more about NavLink
Details
Dynamic Routes
Error Handling
