solidjs / solid-router

A universal router for Solid inspired by Ember and React Router
MIT License
1.1k stars 137 forks source link

Add `useMatches` hook to expose router matches #420

Closed oscartbeaumont closed 1 month ago

oscartbeaumont commented 1 month ago

This PR adds a new useMatches hook which exposes the router's matches.

Usecase

I think this is very useful for implementing a breadcrumb system.

Our pages have something along the lines of:

export const route = {
   info: {
      title: "Route A"
   }
}

and then with the useMatches hook this PR implements, our breadcrumb component can be implemented as such:

import { useMatches } from "@solid/router";
import { createMemo } from "solid-js";

function BreadCrumb() {
   const matches = useMatches();

   // We iterate over each of the matches pulling out the `title` defined on the route as shown in the previous code.
   const routeTitles = createMemo(() =>
      [...matches()]
         .reverse()
         .find((m) => Array.isArray(m.route.info?.title || "")),
   );

   return (
      <div>
         <For each={routeTitles()}>
            {({ route }) => (
               <div>{route.info.title}</div>
            )}
         </For>
      </div>
   );
}

We are actively using these changes in our codebase and it would be really nice to upstream these changes so we don't require a fork. The codebase is open source if it provides more context to our usage. The Breadcrumb component and an example route export.

Prior Art

React Router has a similar feature useMatches. These docs even showcase a Breadcrumb system similar to what I show above.

changeset-bot[bot] commented 1 month ago

🦋 Changeset detected

Latest commit: 68f50fde939405d8cd98310a0cfda953887181c7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package | Name | Type | | --------------- | ----- | | @solidjs/router | Patch |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

oscartbeaumont commented 1 month ago

Turns out useCurrentMatches is exactly this. I don't know how I missed it.