Loading
CORE CONCEPTS
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.
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.
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> ); }
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
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>
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.
| Link | URL | isActive |
|---|---|---|
<NavLink to="/tasks" /> | /tasks | true |
<NavLink to="/tasks" /> | /tasks/123 | true |
<NavLink to="/tasks" end /> | /tasks | true |
<NavLink to="/tasks" end /> | /tasks/123 | false |