Skip to content

Add useMatches hook to expose router matches#420

Closed
oscartbeaumont wants to merge 2 commits intosolidjs:mainfrom
oscartbeaumont:main
Closed

Add useMatches hook to expose router matches#420
oscartbeaumont wants to merge 2 commits intosolidjs:mainfrom
oscartbeaumont:main

Conversation

@oscartbeaumont
Copy link

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
Copy link

changeset-bot bot commented May 17, 2024

🦋 Changeset detected

Latest commit: 68f50fd

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 oscartbeaumont changed the title Add useMatches hook to expose router matches Add useMatches hook to expose router matches May 17, 2024
@oscartbeaumont oscartbeaumont marked this pull request as ready for review May 17, 2024 12:23
@oscartbeaumont
Copy link
Author

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

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

Successfully merging this pull request may close these issues.

1 participant