An open source design system that's fully customizable and agent ready
TypeScript
feat(Link): pass `to` alongside `href` for router compatibility (#2237)
Cindy Zhang7805578527d1
diff --git a/packages/core/src/Link/useXDSLinkComponent.test.tsx b/packages/core/src/Link/useXDSLinkComponent.test.tsxindex 74e145d868..723683d203 100644--- a/packages/core/src/Link/useXDSLinkComponent.test.tsx+++ b/packages/core/src/Link/useXDSLinkComponent.test.tsx@@ -4,10 +4,10 @@* @file useXDSLinkComponent.test.tsx* @input Uses vitest, @testing-library/react, useXDSLinkComponent, XDSLinkProvider* @output Unit tests for useXDSLinkComponent hook and XDSLinkProvider- * @position Testing; validates polymorphic link resolution+ * @position Testing; validates polymorphic link resolution and `to` prop injection*/-import {describe, it, expect} from 'vitest';+import {describe, it, expect, vi} from 'vitest';import {render, screen} from '@testing-library/react';import {forwardRef, type ComponentPropsWithoutRef} from 'react';import {useXDSLinkComponent} from './useXDSLinkComponent';@@ -43,6 +43,25 @@ const AnotherLink = forwardRef<));AnotherLink.displayName = 'AnotherLink';+/**+ * A mock "to"-based router link that reads `to` instead of `href`.+ * Simulates React Router / TanStack Router behavior.+ */+const ToBasedRouterLink = forwardRef<+ HTMLAnchorElement,+ {+ to?: string;+ href?: string;+ children?: React.ReactNode;+ [key: string]: unknown;+ }+>(({to, children, ...props}, ref) => (+ <a ref={ref} href={to} data-router-link data-to={to} {...props}>+ {children}+ </a>+));+ToBasedRouterLink.displayName = 'ToBasedRouterLink';+// =============================================================================// useXDSLinkComponent// =============================================================================@@ -85,6 +104,100 @@ describe('useXDSLinkComponent', () => {});});+// =============================================================================+// `to` prop injection+// =============================================================================++describe('useXDSLinkComponent — to prop', () => {+ it('passes `to` equal to `href` for custom components via provider', () => {+ const spy = vi.fn(+ ({+ children,+ ...props+ }: {+ children?: React.ReactNode;+ [key: string]: unknown;+ }) => (+ <a+ data-testid="spy-link"+ data-to={props.to as string}+ href={props.href as string}>+ {children}+ </a>+ ),+ );+ const SpyLink = forwardRef<+ HTMLAnchorElement,+ {children?: React.ReactNode; [key: string]: unknown}+ >((props, _ref) => spy(props));+ SpyLink.displayName = 'SpyLink';++ render(+ <XDSLinkProvider component={SpyLink}>+ <TestConsumer />+ </XDSLinkProvider>,+ );++ expect(spy).toHaveBeenCalledWith(+ expect.objectContaining({href: '/test', to: '/test'}),+ );+ });++ it('passes `to` equal to `href` for custom components via `as` prop', () => {+ const spy = vi.fn(+ ({+ children,+ ...props+ }: {+ children?: React.ReactNode;+ [key: string]: unknown;+ }) => (+ <a data-testid="spy-link" href={props.href as string}>+ {children}+ </a>+ ),+ );+ const SpyLink = forwardRef<+ HTMLAnchorElement,+ {children?: React.ReactNode; [key: string]: unknown}+ >((props, _ref) => spy(props));+ SpyLink.displayName = 'SpyLink';++ render(<TestConsumer as={SpyLink} />);++ expect(spy).toHaveBeenCalledWith(+ expect.objectContaining({href: '/test', to: '/test'}),+ );+ });++ it('does NOT pass `to` for native <a> (no provider, no as)', () => {+ render(<TestConsumer />);+ const link = screen.getByTestId('resolved-link');+ // Native <a> doesn't use `to`, and we don't wrap it+ expect(link).toHaveAttribute('href', '/test');+ expect(link).not.toHaveAttribute('to');+ });++ it('works with to-based router links (e.g. React Router)', () => {+ render(+ <XDSLinkProvider component={ToBasedRouterLink}>+ <TestConsumer />+ </XDSLinkProvider>,+ );+ const link = screen.getByTestId('resolved-link');+ expect(link).toHaveAttribute('data-router-link');+ expect(link).toHaveAttribute('data-to', '/test');+ expect(link).toHaveAttribute('href', '/test');+ });++ it('to-based router works with as prop override', () => {+ render(<TestConsumer as={ToBasedRouterLink} />);+ const link = screen.getByTestId('resolved-link');+ expect(link).toHaveAttribute('data-router-link');+ expect(link).toHaveAttribute('data-to', '/test');+ });+});+// =============================================================================// XDSLinkProvider// =============================================================================diff --git a/packages/core/src/Link/useXDSLinkComponent.ts b/packages/core/src/Link/useXDSLinkComponent.tsindex 95a0182f9b..f61c4ed0ea 100644--- a/packages/core/src/Link/useXDSLinkComponent.ts+++ b/packages/core/src/Link/useXDSLinkComponent.ts@@ -4,29 +4,62 @@/*** @file useXDSLinkComponent.ts- * @input React useContext, XDSLinkContext, XDSLinkComponentType+ * @input React useContext, useMemo, createElement, forwardRef, XDSLinkContext, XDSLinkComponentType* @output Exports useXDSLinkComponent hook* @position Hook for resolving the link component in XDS components** Resolution order: per-component `as` prop > XDSLinkProvider context > native `<a>`.*+ * When the resolved component is a custom component (not native `<a>`),+ * wraps it to pass `to={href}` alongside `href`. This enables compatibility+ * with routers that use `to` (React Router, TanStack Router)+ * without requiring an adapter component.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Link/index.ts* - /packages/core/src/Link/Link.doc.mjs*/--import {useContext} from 'react';+import {useContext, useMemo, forwardRef, createElement} from 'react';import {XDSLinkContext} from './XDSLinkContext';import type {XDSLinkComponentType} from './types';+/**+ * Creates a wrapper component that passes both `href` and `to` props+ * to the underlying link component. This enables routers that use `to`+ * (React Router, TanStack Router) to work without an adapter.+ *+ * The wrapper is transparent: it forwards refs and all other props unchanged.+ * Native `<a>` elements ignore the unknown `to` prop harmlessly.+ */+function createLinkWithTo(+ Component: XDSLinkComponentType,+): XDSLinkComponentType {+ const LinkWithTo = forwardRef<unknown, {href?: string; to?: string}>(+ ({href, ...rest}, ref) => {+ return createElement(Component, {ref, href, to: href, ...rest});+ },+ );+ LinkWithTo.displayName = `LinkWithTo(${+ typeof Component === 'string'+ ? Component+ : Component.displayName || Component.name || 'Component'+ })`;+ return LinkWithTo as XDSLinkComponentType;+}+/*** Resolves the link component to use.** Priority: `as` prop > `XDSLinkProvider` context > native `<a>`.*+ * When the resolved component is a custom component (not the native `<a>`),+ * it is wrapped to receive both `href` and `to` props set to the same value.+ * This allows `to`-based routers (React Router, TanStack Router) to work+ * out of the box without a manual adapter.+ ** @param as - Per-component override. If provided, takes highest priority.- * @returns The resolved link component.+ * @returns The resolved link component (with `to` injection for custom components).** @example* ```@@ -40,5 +73,14 @@ export function useXDSLinkComponent(as?: XDSLinkComponentType,): XDSLinkComponentType {const ctx = useContext(XDSLinkContext);- return as ?? ctx?.component ?? 'a';+ const resolved = as ?? ctx?.component ?? 'a';++ // Memoize the wrapper to maintain referential stability.+ // The wrapper is only created for custom components (not native <a>).+ return useMemo(() => {+ if (resolved === 'a') {+ return 'a';+ }+ return createLinkWithTo(resolved);+ }, [resolved]);}