Skip to content

Commit

Permalink
Replace useMatches with useParams in LocaleLink and NavLocaleLink com…
Browse files Browse the repository at this point in the history
…ponents (#454)
  • Loading branch information
ttizze authored Dec 23, 2024
2 parents 2263026 + a0c068b commit 7c0760f
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 25 deletions.
11 changes: 2 additions & 9 deletions web/app/components/LocaleLink.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
// LocaleLink.tsx
import { Link, useMatches } from "@remix-run/react";

function useRootData() {
const matches = useMatches();
const rootMatch = matches.find((match) => match.id === "root");
return rootMatch?.data as { locale: string } | undefined;
}
import { Link, useParams } from "@remix-run/react";

export function LocaleLink({
to,
Expand All @@ -16,8 +10,7 @@ export function LocaleLink({
children: React.ReactNode;
className?: string;
}) {
const rootData = useRootData();
const locale = rootData?.locale ?? "en";
const { locale } = useParams();

const path = `/${locale}${to}`;

Expand Down
19 changes: 3 additions & 16 deletions web/app/components/NavLocaleLink.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import { NavLink, type NavLinkProps, useMatches } from "@remix-run/react";

function useRootData() {
const matches = useMatches();
const rootMatch = matches.find((match) => match.id === "root");
return rootMatch?.data as { locale?: string } | undefined;
}
import { NavLink, type NavLinkProps, useParams } from "@remix-run/react";

// NavLinkProps を継承
type NavLocaleLinkProps = Omit<NavLinkProps, "to"> & {
Expand All @@ -17,20 +11,13 @@ export function NavLocaleLink({
children,
...rest
}: NavLocaleLinkProps) {
const rootData = useRootData();
const locale = rootData?.locale ?? "en";
const { locale } = useParams();

// 先頭のスラッシュを削除したうえで "/:locale" を付与
const normalized = to.startsWith("/") ? to.slice(1) : to;
const path = `/${locale}/${normalized}`;

return (
<NavLink
to={path}
// className が「文字列」or「コールバック」どちらでもOK
className={className}
{...rest}
>
<NavLink to={path} className={className} {...rest}>
{children}
</NavLink>
);
Expand Down

0 comments on commit 7c0760f

Please sign in to comment.