#512·wouter

Feature Request: Add `matchRoutes` Function

Author: brtvclCreated Feb 27, 2025Updated Aug 21, 2026

I’d like to request the addition of a matchRoutes function to Wouter. This function is available in react-router, and implementing it in Wouter should require minimal code.

Use Case

The matchRoutes function would allow users to find the active route based on the current location. This is particularly useful for handling layouts or route-based logic efficiently.

Example usage:

javascript
const routes = [
  { path: "/foo", component: <div>Foo</div> },
  { path: "/bar", component: <div>Bar</div>, layout: "red" },
];

const layouts = {
  default: ({ children }) => <div>{children}</div>,
  red: ({ children }) => <div style={{ backgroundColor: "red" }}>{children}</div>,
};

export default function App() {
  const [location] = useLocation();
  const activeRoute = matchRoutes(routes, location);
  const Layout = activeRoute?.layout ? layouts[activeRoute.layout] : layouts.default;

  return (
    <Layout>
      <Routes>
        {routes.map((route) => (
          <Route key={route.path} path={route.path} element={route.component} />
        ))}
      </Routes>
    </Layout>
  );
}

Example Implementation

This is the implementation I currently use in my project. (~160 bytes, unminified)

javascript
import { parse } from "regexparam";

function matchRoutes(routes, location) {
  return routes.find((route) => {
    const regex = parse(route.path);
    return regex.pattern.test(location);
  });
}

Having this built into the library would prevent redundant loops (like in my example implementation) when matching routes, as Wouter itself already performs route matching internally.

Would love to hear your thoughts on this! Thanks for the awesome work on Wouter!