Upgrade to React Router v6 (#2919)

This commit is contained in:
Quentin Gliech
2025-01-06 18:00:20 +01:00
committed by GitHub
parent 46a82b2c39
commit b5f4a07868
19 changed files with 112 additions and 254 deletions

View File

@@ -9,42 +9,27 @@ import {
type ComponentPropsWithoutRef,
forwardRef,
type MouseEvent,
useCallback,
useMemo,
} from "react";
import { Link as CpdLink } from "@vector-im/compound-web";
import { useHistory } from "react-router-dom";
import { createPath, type LocationDescriptor, type Path } from "history";
import { type LinkProps, useHref, useLinkClickHandler } from "react-router-dom";
import classNames from "classnames";
import { useLatest } from "../useLatest";
import styles from "./Link.module.css";
export function useLink(
to: LocationDescriptor,
to: LinkProps["to"],
state?: unknown,
): [Path, (e: MouseEvent) => void] {
const latestState = useLatest(state);
const history = useHistory();
const path = useMemo(
() => (typeof to === "string" ? to : createPath(to)),
[to],
);
const onClick = useCallback(
(e: MouseEvent) => {
e.preventDefault();
history.push(to, latestState.current);
},
[history, to, latestState],
);
): [string, (e: MouseEvent<HTMLAnchorElement>) => void] {
const href = useHref(to);
const onClick = useLinkClickHandler(to, { state });
return [path, onClick];
return [href, onClick];
}
type Props = Omit<
ComponentPropsWithoutRef<typeof CpdLink>,
"href" | "onClick"
> & { to: LocationDescriptor; state?: unknown };
> & { to: LinkProps["to"]; state?: unknown };
/**
* A version of Compound's link component that integrates with our router setup.

View File

@@ -7,22 +7,22 @@ Please see LICENSE in the repository root for full details.
import { type ComponentPropsWithoutRef, forwardRef } from "react";
import { Button } from "@vector-im/compound-web";
import { type LocationDescriptor } from "history";
import type { LinkProps } from "react-router-dom";
import { useLink } from "./Link";
type Props = Omit<
ComponentPropsWithoutRef<typeof Button<"a">>,
"as" | "href"
> & { to: LocationDescriptor };
> & { to: LinkProps["to"]; state?: unknown };
/**
* A version of Compound's button component that acts as a link and integrates
* with our router setup.
*/
export const LinkButton = forwardRef<HTMLAnchorElement, Props>(
function LinkButton({ to, ...props }, ref) {
const [path, onClick] = useLink(to);
function LinkButton({ to, state, ...props }, ref) {
const [path, onClick] = useLink(to, state);
return <Button as="a" ref={ref} {...props} href={path} onClick={onClick} />;
},
);