Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Add matchRoutes Function #512

Open
brtvcl opened this issue Feb 27, 2025 · 0 comments
Open

Feature Request: Add matchRoutes Function #512

brtvcl opened this issue Feb 27, 2025 · 0 comments

Comments

@brtvcl
Copy link

brtvcl commented Feb 27, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant