molefrog / molefrog/wouter

Feature Request: Add `matchRoutes` Function

Open
#512 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
7.9k
Forks
190
Avg merge
12h 50m
Merged PRs (30d)
3

Description

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:
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)

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! 🚀

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating Wouter's existing route-matching code and public exports, then compare its matching behavior with the proposed regexparam-based example. Done means exposing matchRoutes so it selects the active route for a location and supports the documented usage without redundant matching.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
frontend
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.