Custom Link

This example shows how to create a custom <Link> that renders something special when the URL is the same as the one the <Link> points to. It builds directly on useMatch() instead of the removed useRouteMatch() hook – since useMatch() takes an arbitrary pattern rather than reading the nearest matched route, it fits this use case just as well.


import React from "react";
import { BrowserRouter as Router, Routes, Route, Link, useMatch } from "react-router";

export default function CustomLinkExample() {
  return (
    <Router>
      <div>
        <OldSchoolMenuLink activeOnlyWhenExact={true} to="/" label="Home" />
        <OldSchoolMenuLink to="/about" label="About" />
        <hr />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </div>
    </Router>
  );
}
function OldSchoolMenuLink({ label, to, activeOnlyWhenExact }) {
  // A trailing /* makes the match non-exact, i.e. also active on sub-paths
  let match = useMatch(activeOnlyWhenExact ? to : `${to}/*`);
  return (
    <div className={match ? "active" : ""}>
      {match && "> "}
      <Link to={to}>{label}</Link>
    </div>
  );
}
function Home() { return (<div><h2>Home</h2></div>); }
function About() { return (<div><h2>About</h2></div>); }