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.

src/components/ActiveLink.tsx
tsximport 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> ); }

Rasengan.js provides a NavLink component that makes it easier to define active links.

src/components/NavLink.tsx
tsximport 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> ); }
Active stateThe `NavLink` component becomes active when the current route start with the `to` prop value.
txtWhen 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.

tsx<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.

LinkURLisActive
<NavLink to="/tasks" />/taskstrue
<NavLink to="/tasks" />/tasks/123true
<NavLink to="/tasks" end />/taskstrue
<NavLink to="/tasks" end />/tasks/123false
Learn more about NavLink
Details
Dynamic Routes
Error Handling