Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(link): add polymorphic link support with XDSLinkProvider and per-component as prop (#337)

Cindy Zhang8b54a79986b5
diff --git a/apps/sandbox/src/app/Sidebar.tsx b/apps/sandbox/src/app/Sidebar.tsx
index 42c3b061ee..f9f0099705 100644
--- a/apps/sandbox/src/app/Sidebar.tsx
+++ b/apps/sandbox/src/app/Sidebar.tsx
@@ -21,6 +21,7 @@ const pages = [
{name: 'Example', href: '/pages/example/'},
{name: 'Navigation', href: '/pages/navigation/'},
{name: 'TopNav Menu', href: '/pages/topnav-menu/'},
+ {name: 'Polymorphic Link', href: '/pages/polymorphic-link/'},
];
const styles = stylex.create({
diff --git a/apps/sandbox/src/app/pages/polymorphic-link/page.tsx b/apps/sandbox/src/app/pages/polymorphic-link/page.tsx
new file mode 100644
index 0000000000..e6a42022e4
--- /dev/null
+++ b/apps/sandbox/src/app/pages/polymorphic-link/page.tsx
@@ -0,0 +1,304 @@
+'use client';
+
+import {
+ useState,
+ forwardRef,
+ type AnchorHTMLAttributes,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {XDSVStack, XDSHStack} from '@xds/core/Layout';
+import {XDSText, XDSHeading} from '@xds/core/Text';
+import {XDSButton} from '@xds/core/Button';
+import {XDSDivider} from '@xds/core';
+import {XDSTopNav, XDSTopNavTitle, XDSTopNavItem} from '@xds/core/TopNav';
+import {XDSSideNav, XDSSideNavItem} from '@xds/core/SideNav';
+import {XDSBreadcrumbs, XDSBreadcrumbItem} from '@xds/core/Breadcrumbs';
+import {XDSTabList, XDSTab} from '@xds/core/TabList';
+import {XDSLink, XDSLinkProvider} from '@xds/core/Link';
+
+// =============================================================================
+// Simulated framework link components
+// =============================================================================
+
+const styles = stylex.create({
+ container: {
+ maxWidth: 960,
+ },
+ navWrapper: {
+ border: '1px solid #e0e0e0',
+ borderRadius: 8,
+ overflow: 'hidden',
+ },
+ log: {
+ fontFamily: 'monospace',
+ fontSize: '0.8rem',
+ backgroundColor: '#f5f5f5',
+ padding: '0.75rem 1rem',
+ borderRadius: 6,
+ maxHeight: 200,
+ overflow: 'auto',
+ whiteSpace: 'pre-wrap',
+ },
+ customLinkIndicator: {
+ outline: '2px dashed #3b82f6',
+ outlineOffset: -2,
+ },
+ sidenavWrapper: {
+ width: 240,
+ border: '1px solid #e0e0e0',
+ borderRadius: 8,
+ overflow: 'hidden',
+ },
+});
+
+/**
+ * Simulated Next.js-like Link for demo purposes.
+ * Intercepts navigation and logs to console instead of full page reload.
+ * Renders with a blue dashed outline to visually identify it.
+ */
+const SimulatedNextLink = forwardRef<
+ HTMLAnchorElement,
+ AnchorHTMLAttributes<HTMLAnchorElement> & {children?: ReactNode}
+>(function SimulatedNextLink({href, onClick, children, ...props}, ref) {
+ return (
+ <a
+ ref={ref}
+ href={href}
+ onClick={e => {
+ e.preventDefault();
+
+ console.log(`[SimulatedNextLink] Client-side navigate to: ${href}`);
+ onClick?.(e);
+ }}
+ {...stylex.props(styles.customLinkIndicator)}
+ {...props}>
+ {children}
+ </a>
+ );
+});
+
+/**
+ * Another custom link for demonstrating per-component `as` override.
+ * Renders with a green dashed outline.
+ */
+const GreenLink = forwardRef<
+ HTMLAnchorElement,
+ AnchorHTMLAttributes<HTMLAnchorElement> & {children?: ReactNode}
+>(function GreenLink({href, onClick, children, style, ...props}, ref) {
+ return (
+ <a
+ ref={ref}
+ href={href}
+ onClick={e => {
+ e.preventDefault();
+
+ console.log(`[GreenLink] Navigate to: ${href}`);
+ onClick?.(e);
+ }}
+ style={{...style, outline: '2px dashed #22c55e', outlineOffset: -2}}
+ {...props}>
+ {children}
+ </a>
+ );
+});
+
+// =============================================================================
+// Demo page
+// =============================================================================
+
+export default function PolymorphicLinkPage() {
+ const [tab, setTab] = useState('overview');
+
+ return (
+ <div {...stylex.props(styles.container)}>
+ <XDSVStack gap="space6">
+ <XDSVStack gap="space2">
+ <XDSHeading level={1}>Polymorphic Link</XDSHeading>
+ <XDSText type="body" color="secondary">
+ XDS components that render links can use a custom link component
+ instead of native {'<a>'}. Set it globally via XDSLinkProvider or
+ per-component via the{' '}
+ <XDSText type="body" weight="bold">
+ as
+ </XDSText>{' '}
+ prop.
+ </XDSText>
+ </XDSVStack>
+
+ <XDSDivider />
+
+ {/* ================================================================= */}
+ {/* Section 1: Provider Demo */}
+ {/* ================================================================= */}
+ <XDSVStack gap="space3">
+ <XDSHeading level={2}>Provider Demo</XDSHeading>
+ <XDSText type="body" color="secondary">
+ All components below are wrapped in{' '}
+ <XDSText type="body" weight="bold">
+ XDSLinkProvider
+ </XDSText>{' '}
+ with a simulated Next.js Link (blue dashed outline). Open the
+ browser console to see navigation logs.
+ </XDSText>
+
+ <XDSLinkProvider component={SimulatedNextLink}>
+ <XDSVStack gap="space4">
+ {/* TopNav */}
+ <XDSVStack gap="space1">
+ <XDSText type="supporting" weight="bold">
+ XDSTopNav
+ </XDSText>
+ <div {...stylex.props(styles.navWrapper)}>
+ <XDSTopNav
+ label="Provider demo navigation"
+ title={<XDSTopNavTitle title="My App" />}
+ startContent={
+ <>
+ <XDSTopNavItem label="Home" href="/" isSelected />
+ <XDSTopNavItem label="Products" href="/products" />
+ <XDSTopNavItem label="About" href="/about" />
+ </>
+ }
+ />
+ </div>
+ </XDSVStack>
+
+ {/* Breadcrumbs */}
+ <XDSVStack gap="space1">
+ <XDSText type="supporting" weight="bold">
+ XDSBreadcrumbs
+ </XDSText>
+ <XDSBreadcrumbs label="Provider breadcrumbs">
+ <XDSBreadcrumbItem href="/">Home</XDSBreadcrumbItem>
+ <XDSBreadcrumbItem href="/products">
+ Products
+ </XDSBreadcrumbItem>
+ <XDSBreadcrumbItem isCurrent>Widget</XDSBreadcrumbItem>
+ </XDSBreadcrumbs>
+ </XDSVStack>
+
+ {/* TabList */}
+ <XDSVStack gap="space1">
+ <XDSText type="supporting" weight="bold">
+ XDSTabList (with href)
+ </XDSText>
+ <XDSTabList value={tab} onChange={setTab}>
+ <XDSTab value="overview" label="Overview" href="/overview" />
+ <XDSTab value="details" label="Details" href="/details" />
+ <XDSTab value="reviews" label="Reviews" href="/reviews" />
+ </XDSTabList>
+ </XDSVStack>
+
+ {/* SideNav */}
+ <XDSVStack gap="space1">
+ <XDSText type="supporting" weight="bold">
+ XDSSideNav
+ </XDSText>
+ <div {...stylex.props(styles.sidenavWrapper)}>
+ <XDSSideNav label="Provider sidenav">
+ <XDSSideNavItem
+ label="Dashboard"
+ href="/dashboard"
+ isSelected
+ />
+ <XDSSideNavItem label="Settings" href="/settings" />
+ <XDSSideNavItem label="Profile" href="/profile" />
+ </XDSSideNav>
+ </div>
+ </XDSVStack>
+
+ {/* XDSLink */}
+ <XDSVStack gap="space1">
+ <XDSText type="supporting" weight="bold">
+ XDSLink
+ </XDSText>
+ <XDSLink label="Documentation link" href="/docs">
+ Go to documentation
+ </XDSLink>
+ </XDSVStack>
+ </XDSVStack>
+ </XDSLinkProvider>
+ </XDSVStack>
+
+ <XDSDivider />
+
+ {/* ================================================================= */}
+ {/* Section 2: Per-component `as` override */}
+ {/* ================================================================= */}
+ <XDSVStack gap="space3">
+ <XDSHeading level={2}>Per-Component Override</XDSHeading>
+ <XDSText type="body" color="secondary">
+ The{' '}
+ <XDSText type="body" weight="bold">
+ as
+ </XDSText>{' '}
+ prop overrides the provider for a single component. Below, the
+ provider sets the blue link, but &quot;Products&quot; uses a green
+ link via{' '}
+ <XDSText type="body" weight="bold">
+ as={'{GreenLink}'}
+ </XDSText>
+ .
+ </XDSText>
+
+ <XDSLinkProvider component={SimulatedNextLink}>
+ <div {...stylex.props(styles.navWrapper)}>
+ <XDSTopNav
+ label="Override demo navigation"
+ title={<XDSTopNavTitle title="Override Demo" />}
+ startContent={
+ <>
+ <XDSTopNavItem label="Home" href="/" isSelected />
+ <XDSTopNavItem
+ label="Products"
+ href="/products"
+ as={GreenLink}
+ />
+ <XDSTopNavItem label="About" href="/about" />
+ </>
+ }
+ />
+ </div>
+ </XDSLinkProvider>
+ </XDSVStack>
+
+ <XDSDivider />
+
+ {/* ================================================================= */}
+ {/* Section 3: Default behavior (no provider) */}
+ {/* ================================================================= */}
+ <XDSVStack gap="space3">
+ <XDSHeading level={2}>Default Behavior</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Without a provider or{' '}
+ <XDSText type="body" weight="bold">
+ as
+ </XDSText>{' '}
+ prop, components render native {'<a>'} elements as usual.
+ </XDSText>
+
+ <div {...stylex.props(styles.navWrapper)}>
+ <XDSTopNav
+ label="Default navigation"
+ title={<XDSTopNavTitle title="Default" />}
+ startContent={
+ <>
+ <XDSTopNavItem label="Home" href="#home" isSelected />
+ <XDSTopNavItem label="Products" href="#products" />
+ <XDSTopNavItem label="About" href="#about" />
+ </>
+ }
+ />
+ </div>
+
+ <XDSBreadcrumbs label="Default breadcrumbs">
+ <XDSBreadcrumbItem href="#home">Home</XDSBreadcrumbItem>
+ <XDSBreadcrumbItem href="#products">Products</XDSBreadcrumbItem>
+ <XDSBreadcrumbItem isCurrent>Current Page</XDSBreadcrumbItem>
+ </XDSBreadcrumbs>
+ </XDSVStack>
+ </XDSVStack>
+ </div>
+ );
+}
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
index 44d6175678..6aa4f8f17f 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
@@ -11,6 +11,8 @@
* - /apps/storybook/stories/Breadcrumbs.stories.tsx
*/
+'use client';
+
import {useContext, type ReactNode, type MouseEvent} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
@@ -20,12 +22,20 @@ import {
lineHeightVars,
} from '../theme/tokens.stylex';
import {BreadcrumbCtx} from './XDSBreadcrumbs';
+import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+import type {XDSLinkComponentType} from '../Link/types';
// =============================================================================
// Props
// =============================================================================
export interface XDSBreadcrumbItemProps {
+ /**
+ * Custom component to render instead of `<a>` for breadcrumb links.
+ * Overrides the provider-level default set by XDSLinkProvider.
+ * Only applies for non-current items. Must accept href, className, style, and children props.
+ */
+ as?: XDSLinkComponentType;
/**
* Label content of the breadcrumb item.
*/
@@ -123,6 +133,7 @@ const itemStyles = stylex.create({
* ```
*/
export function XDSBreadcrumbItem({
+ as,
children,
href,
onClick,
@@ -132,6 +143,7 @@ export function XDSBreadcrumbItem({
}: XDSBreadcrumbItemProps) {
const ctx = useContext(BreadcrumbCtx);
const isCurrent = isCurrentProp ?? ctx.isAutoLast;
+ const LinkComponent = useXDSLinkComponent(as);
const isSupporting = ctx.variant === 'supporting';
const content = (
@@ -171,7 +183,7 @@ export function XDSBreadcrumbItem({
isSupporting ? itemStyles.supportingSize : itemStyles.defaultSize,
)}
data-testid={testId}>
- <a
+ <LinkComponent
href={href}
onClick={onClick}
{...stylex.props(
@@ -179,7 +191,7 @@ export function XDSBreadcrumbItem({
isSupporting ? itemStyles.supportingLink : itemStyles.defaultLink,
)}>
{content}
- </a>
+ </LinkComponent>
</li>
);
}
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx
index 662a380ba2..d3b8caa55d 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbs.test.tsx
@@ -1,8 +1,19 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {forwardRef, type ComponentPropsWithoutRef} from 'react';
import {XDSBreadcrumbs} from './XDSBreadcrumbs';
import {XDSBreadcrumbItem} from './XDSBreadcrumbItem';
+import {XDSLinkProvider} from '../Link/XDSLinkProvider';
+
+const CustomLink = forwardRef<HTMLAnchorElement, ComponentPropsWithoutRef<'a'>>(
+ ({children, ...props}, ref) => (
+ <a ref={ref} data-custom-link {...props}>
+ {children}
+ </a>
+ ),
+);
+CustomLink.displayName = 'CustomLink';
describe('XDSBreadcrumbs', () => {
it('renders a nav landmark with aria-label', () => {
@@ -246,4 +257,51 @@ describe('XDSBreadcrumbItem', () => {
expect(last).toHaveAttribute('aria-current', 'page');
expect(last.tagName).toBe('SPAN');
});
+
+ it('renders custom component for non-current items when as is provided', () => {
+ render(
+ <XDSBreadcrumbs>
+ <XDSBreadcrumbItem href="/" as={CustomLink}>
+ Home
+ </XDSBreadcrumbItem>
+ <XDSBreadcrumbItem isCurrent>Current</XDSBreadcrumbItem>
+ </XDSBreadcrumbs>,
+ );
+ const link = screen.getByRole('link', {name: 'Home'});
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).toHaveAttribute('href', '/');
+ });
+
+ it('does not apply as to current item (renders as span)', () => {
+ render(
+ <XDSBreadcrumbs>
+ <XDSBreadcrumbItem href="/">Home</XDSBreadcrumbItem>
+ <XDSBreadcrumbItem isCurrent as={CustomLink}>
+ Current
+ </XDSBreadcrumbItem>
+ </XDSBreadcrumbs>,
+ );
+ const current = screen.getByText('Current');
+ expect(current.tagName).toBe('SPAN');
+ expect(current).not.toHaveAttribute('data-custom-link');
+ });
+
+ it('renders custom component from XDSLinkProvider for non-current items', () => {
+ render(
+ <XDSLinkProvider component={CustomLink}>
+ <XDSBreadcrumbs>
+ <XDSBreadcrumbItem href="/">Home</XDSBreadcrumbItem>
+ <XDSBreadcrumbItem href="/projects">Projects</XDSBreadcrumbItem>
+ <XDSBreadcrumbItem isCurrent>Current</XDSBreadcrumbItem>
+ </XDSBreadcrumbs>
+ </XDSLinkProvider>,
+ );
+ const homeLink = screen.getByRole('link', {name: 'Home'});
+ expect(homeLink).toHaveAttribute('data-custom-link');
+ const projectsLink = screen.getByRole('link', {name: 'Projects'});
+ expect(projectsLink).toHaveAttribute('data-custom-link');
+ // Current item is still a span
+ const current = screen.getByText('Current');
+ expect(current.tagName).toBe('SPAN');
+ });
});
diff --git a/packages/core/src/Link/README.md b/packages/core/src/Link/README.md
index 8e9790140e..bbd964b0a6 100644
--- a/packages/core/src/Link/README.md
+++ b/packages/core/src/Link/README.md
@@ -1,6 +1,6 @@
# Link
-XDSLink component for styled anchor links with multiple variants and features.
+XDSLink component for styled anchor links with multiple variants and features, plus polymorphic link infrastructure for rendering custom link components (Next.js Link, React Router Link, etc.).
<!-- SYNC: When files in this directory change, update this document. -->
@@ -14,6 +14,7 @@ XDSLink component for styled anchor links with multiple variants and features.
- **Standalone mode**: Applies base font sizing for independent links
- **Disabled state**: Visual and interaction disabled
- **Focus visible**: Accessible focus outline
+- **Polymorphic link**: Render as a custom component via `as` prop or `XDSLinkProvider`
## Usage
@@ -47,21 +48,70 @@ import { XDSLink } from '@xds/core/Link';
<XDSLink label="Disabled" href="/disabled" isDisabled>Disabled Link</XDSLink>
```
+## Polymorphic Link
+
+All XDS components that render links (`XDSLink`, `XDSTopNavItem`, `XDSSideNavItem`, `XDSBreadcrumbItem`, `XDSTab`) support rendering as a custom link component instead of the native `<a>` element. This enables framework-specific routing (Next.js, React Router, etc.).
+
+### Provider (global default)
+
+Wrap your app in `XDSLinkProvider` to set the default link component for all XDS components in the subtree:
+
+```tsx
+import Link from 'next/link';
+import {XDSLinkProvider} from '@xds/core/Link';
+
+<XDSLinkProvider component={Link}>
+ <App />
+</XDSLinkProvider>;
+```
+
+### Per-component override (`as` prop)
+
+Override the provider for a single component using the `as` prop:
+
+```tsx
+import {Link as RouterLink} from 'react-router-dom';
+
+<XDSLink label="Docs" href="/docs" as={RouterLink}>
+ Docs
+</XDSLink>;
+```
+
+### Resolution order
+
+1. Per-component `as` prop (highest priority)
+2. `XDSLinkProvider` context
+3. Native `<a>` element (default)
+
+### Hook: `useXDSLinkComponent`
+
+For custom components that need to resolve the link component:
+
+```tsx
+import {useXDSLinkComponent} from '@xds/core/Link';
+
+function MyComponent({as}: {as?: XDSLinkComponentType}) {
+ const LinkComponent = useXDSLinkComponent(as);
+ return <LinkComponent href="/foo">Click me</LinkComponent>;
+}
+```
+
## Props
-| Prop | Type | Default | Description |
-| ---------------- | ------------------------------------ | ----------- | ----------------------------------- |
-| `label` | `string` | — | Accessible label (required) |
-| `href` | `string` | — | Link destination URL |
-| `variant` | `'default' \| 'subtle' \| 'inherit'` | `'default'` | Visual style variant |
-| `hasUnderline` | `boolean` | `false` | Always show underline |
-| `isDisabled` | `boolean` | `false` | Disables the link |
-| `isExternalLink` | `boolean` | `false` | Opens in new tab with external icon |
-| `target` | `string` | — | Where to open linked document |
-| `onClick` | `MouseEventHandler` | — | Click event handler |
-| `tooltip` | `string` | — | Tooltip text displayed on hover |
-| `isStandalone` | `boolean` | `false` | Applies base font sizing |
-| `children` | `ReactNode` | — | Link content (required) |
+| Prop | Type | Default | Description |
+| ---------------- | ------------------------------------ | ----------- | ------------------------------------------- |
+| `as` | `XDSLinkComponentType` | — | Custom component to render instead of `<a>` |
+| `label` | `string` | — | Accessible label (required) |
+| `href` | `string` | — | Link destination URL |
+| `variant` | `'default' \| 'subtle' \| 'inherit'` | `'default'` | Visual style variant |
+| `hasUnderline` | `boolean` | `false` | Always show underline |
+| `isDisabled` | `boolean` | `false` | Disables the link |
+| `isExternalLink` | `boolean` | `false` | Opens in new tab with external icon |
+| `target` | `string` | — | Where to open linked document |
+| `onClick` | `MouseEventHandler` | — | Click event handler |
+| `tooltip` | `string` | — | Tooltip text displayed on hover |
+| `isStandalone` | `boolean` | `false` | Applies base font sizing |
+| `children` | `ReactNode` | — | Link content (required) |
## Theming
@@ -87,11 +137,16 @@ const theme: Theme = {
## Files
-| File | Role | Purpose |
-| ------------------ | ----- | ----------------------------------- |
-| `index.ts` | Entry | Exports XDSLink component and types |
-| `XDSLink.tsx` | Core | XDSLink component implementation |
-| `XDSLink.test.tsx` | Test | Unit tests for XDSLink component |
+| File | Role | Purpose |
+| ------------------------------ | -------- | ------------------------------------------------ |
+| `index.ts` | Entry | Exports all public Link components, hooks, types |
+| `XDSLink.tsx` | Core | XDSLink component implementation |
+| `XDSLink.test.tsx` | Test | Unit tests for XDSLink component |
+| `XDSLinkProvider.tsx` | Provider | Sets default link component for subtree |
+| `XDSLinkContext.ts` | Context | React context definition for link provider |
+| `useXDSLinkComponent.ts` | Hook | Resolves link component (as > provider > `<a>`) |
+| `useXDSLinkComponent.test.tsx` | Test | Unit tests for hook and provider |
+| `types.ts` | Types | Shared XDSLinkComponentType definition |
## Implementation Notes
@@ -101,3 +156,6 @@ const theme: Theme = {
- `isExternalLink` automatically sets `target="_blank"` and `rel="noopener noreferrer"` for security
- Disabled state uses `aria-disabled` and `pointer-events: none` for accessibility
- Tooltip wraps the link in `XDSTooltip` component when provided
+- `XDSLinkComponentType` is `React.ElementType`, allowing both string tags (`'a'`) and custom components
+- `XDSLinkContext` is separated from `XDSLinkProvider` (mirrors `ThemeContext`/`XDSTheme` pattern) so consumers can import the context without the full provider
+- `XDSLinkProvider` memoizes its context value to prevent unnecessary re-renders
diff --git a/packages/core/src/Link/XDSLink.test.tsx b/packages/core/src/Link/XDSLink.test.tsx
index 1206d59570..7d72b05ca1 100644
--- a/packages/core/src/Link/XDSLink.test.tsx
+++ b/packages/core/src/Link/XDSLink.test.tsx
@@ -10,7 +10,18 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {forwardRef, type ComponentPropsWithoutRef} from 'react';
import {XDSLink} from './XDSLink';
+import {XDSLinkProvider} from './XDSLinkProvider';
+
+const CustomLink = forwardRef<HTMLAnchorElement, ComponentPropsWithoutRef<'a'>>(
+ ({children, ...props}, ref) => (
+ <a ref={ref} data-custom-link {...props}>
+ {children}
+ </a>
+ ),
+);
+CustomLink.displayName = 'CustomLink';
describe('XDSLink', () => {
it('renders children as link text', () => {
@@ -164,4 +175,48 @@ describe('XDSLink', () => {
const link = screen.getByRole('link', {name: 'Settings'});
expect(link).toBeInTheDocument();
});
+
+ it('renders custom component when as is provided', () => {
+ render(
+ <XDSLink label="Custom" href="/custom" as={CustomLink}>
+ Custom Link
+ </XDSLink>,
+ );
+ const link = screen.getByRole('link', {name: 'Custom'});
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).toHaveAttribute('href', '/custom');
+ });
+
+ it('renders custom component from XDSLinkProvider', () => {
+ render(
+ <XDSLinkProvider component={CustomLink}>
+ <XDSLink label="Provider" href="/provider">
+ Provider Link
+ </XDSLink>
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByRole('link', {name: 'Provider'});
+ expect(link).toHaveAttribute('data-custom-link');
+ });
+
+ it('as prop overrides XDSLinkProvider', () => {
+ const AnotherLink = forwardRef<
+ HTMLAnchorElement,
+ ComponentPropsWithoutRef<'a'>
+ >(({children, ...props}, ref) => (
+ <a ref={ref} data-another-link {...props}>
+ {children}
+ </a>
+ ));
+ render(
+ <XDSLinkProvider component={AnotherLink}>
+ <XDSLink label="Override" href="/override" as={CustomLink}>
+ Override Link
+ </XDSLink>
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByRole('link', {name: 'Override'});
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).not.toHaveAttribute('data-another-link');
+ });
});
diff --git a/packages/core/src/Link/XDSLink.tsx b/packages/core/src/Link/XDSLink.tsx
index aba011bd82..e139131bf1 100644
--- a/packages/core/src/Link/XDSLink.tsx
+++ b/packages/core/src/Link/XDSLink.tsx
@@ -39,6 +39,8 @@ import type {
XDSTextWeight,
XDSTextDisplay,
} from '../theme/types';
+import {useXDSLinkComponent} from './useXDSLinkComponent';
+import type {XDSLinkComponentType} from './types';
/**
* Base link styles
@@ -123,6 +125,12 @@ export interface XDSLinkProps extends Omit<
AnchorHTMLAttributes<HTMLAnchorElement>,
'children'
> {
+ /**
+ * Custom component to render instead of `<a>`.
+ * Overrides the provider-level default set by XDSLinkProvider.
+ * Must accept href, className, style, and children props.
+ */
+ as?: XDSLinkComponentType;
/**
* Accessible label for the link (required for accessibility).
* Used as aria-label when content is not self-descriptive.
@@ -226,6 +234,7 @@ export interface XDSLinkProps extends Omit<
export const XDSLink = forwardRef<HTMLAnchorElement, XDSLinkProps>(
(
{
+ as,
label,
href,
hasUnderline = false,
@@ -247,6 +256,7 @@ export const XDSLink = forwardRef<HTMLAnchorElement, XDSLinkProps>(
},
ref,
) => {
+ const LinkComponent = useXDSLinkComponent(as);
// Determine target and rel based on isExternalLink
const computedTarget = isExternalLink ? '_blank' : target;
const computedRel = isExternalLink
@@ -260,7 +270,7 @@ export const XDSLink = forwardRef<HTMLAnchorElement, XDSLinkProps>(
const rootOverride = themeContext?.theme.components?.link?.root;
const linkElement = (
- <a
+ <LinkComponent
ref={ref}
href={href}
target={computedTarget}
@@ -290,7 +300,7 @@ export const XDSLink = forwardRef<HTMLAnchorElement, XDSLinkProps>(
{isExternalLink && (
<XDSIcon icon="externalLink" size="xsm" color="inherit" />
)}
- </a>
+ </LinkComponent>
);
// Wrap with tooltip if provided
diff --git a/packages/core/src/Link/XDSLinkContext.ts b/packages/core/src/Link/XDSLinkContext.ts
new file mode 100644
index 0000000000..366facafdd
--- /dev/null
+++ b/packages/core/src/Link/XDSLinkContext.ts
@@ -0,0 +1,32 @@
+/**
+ * @file XDSLinkContext.ts
+ * @input React createContext, XDSLinkComponentType
+ * @output Exports XDSLinkContext and XDSLinkContextValue
+ * @position Context definition for polymorphic link support
+ *
+ * Separated from XDSLinkProvider.tsx to allow components to consume
+ * the context without pulling in the full provider implementation.
+ * Follows the ThemeContext.ts / XDSTheme.tsx pattern.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Link/XDSLinkProvider.tsx
+ * - /packages/core/src/Link/useXDSLinkComponent.ts
+ * - /packages/core/src/Link/index.ts
+ * - /packages/core/src/Link/README.md
+ */
+
+import {createContext} from 'react';
+import type {XDSLinkComponentType} from './types';
+
+/**
+ * Context value for the link provider.
+ */
+export interface XDSLinkContextValue {
+ component: XDSLinkComponentType;
+}
+
+/**
+ * Context for providing a custom link component to all XDS components.
+ * Defaults to null (components fall back to native `<a>`).
+ */
+export const XDSLinkContext = createContext<XDSLinkContextValue | null>(null);
diff --git a/packages/core/src/Link/XDSLinkProvider.tsx b/packages/core/src/Link/XDSLinkProvider.tsx
new file mode 100644
index 0000000000..88f7e5bd2b
--- /dev/null
+++ b/packages/core/src/Link/XDSLinkProvider.tsx
@@ -0,0 +1,57 @@
+/**
+ * @file XDSLinkProvider.tsx
+ * @input React, XDSLinkContext, XDSLinkComponentType
+ * @output Exports XDSLinkProvider component and XDSLinkProviderProps
+ * @position Provider component for polymorphic link support
+ *
+ * Sets the default link component for all XDS components in the subtree.
+ * Individual components can still override via the `as` prop.
+ *
+ * @example
+ * ```tsx
+ * import Link from 'next/link';
+ *
+ * <XDSLinkProvider component={Link}>
+ * <App />
+ * </XDSLinkProvider>
+ * ```
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Link/index.ts
+ * - /packages/core/src/Link/README.md
+ */
+
+'use client';
+
+import {useMemo, type ReactNode} from 'react';
+import {XDSLinkContext} from './XDSLinkContext';
+import type {XDSLinkComponentType} from './types';
+
+export interface XDSLinkProviderProps {
+ /**
+ * The component to use for all link elements in the subtree.
+ * Must accept href, className, style, and children props.
+ *
+ * @example
+ * ```tsx
+ * import Link from 'next/link';
+ * <XDSLinkProvider component={Link}>
+ * ```
+ */
+ component: XDSLinkComponentType;
+ children: ReactNode;
+}
+
+/**
+ * Provides a custom link component to all XDS components in the subtree.
+ *
+ * Wrap your app (or a section of it) in XDSLinkProvider to replace
+ * native `<a>` elements with your framework's link component
+ * (e.g., Next.js Link, React Router Link).
+ */
+export function XDSLinkProvider({component, children}: XDSLinkProviderProps) {
+ const value = useMemo(() => ({component}), [component]);
+ return (
+ <XDSLinkContext.Provider value={value}>{children}</XDSLinkContext.Provider>
+ );
+}
diff --git a/packages/core/src/Link/index.ts b/packages/core/src/Link/index.ts
index 95f86b3516..c8e94e9789 100644
--- a/packages/core/src/Link/index.ts
+++ b/packages/core/src/Link/index.ts
@@ -1,7 +1,7 @@
/**
* @file index.ts
- * @input Imports XDSLink component and types from XDSLink.tsx
- * @output Exports XDSLink, XDSLinkProps
+ * @input Imports XDSLink, XDSLinkProvider, useXDSLinkComponent, types
+ * @output Exports all public Link components, hooks, and types
* @position Component entry point; re-exported by /packages/core/src/index.ts
*
* SYNC: When modified, update this header and /packages/core/src/Link/README.md
@@ -9,3 +9,10 @@
export {XDSLink} from './XDSLink';
export type {XDSLinkProps} from './XDSLink';
+
+export {XDSLinkProvider} from './XDSLinkProvider';
+export type {XDSLinkProviderProps} from './XDSLinkProvider';
+
+export {useXDSLinkComponent} from './useXDSLinkComponent';
+
+export type {XDSLinkComponentType} from './types';
diff --git a/packages/core/src/Link/types.ts b/packages/core/src/Link/types.ts
new file mode 100644
index 0000000000..f3e26440cf
--- /dev/null
+++ b/packages/core/src/Link/types.ts
@@ -0,0 +1,21 @@
+/**
+ * @file types.ts
+ * @input React ElementType
+ * @output Exports XDSLinkComponentType
+ * @position Shared types for polymorphic link infrastructure
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Link/index.ts
+ * - /packages/core/src/Link/README.md
+ */
+
+import type {ElementType} from 'react';
+
+/**
+ * A component that can be used as a link.
+ * Accepts at minimum: href, className, style, children.
+ *
+ * Uses `ElementType` (not `ComponentType`) so that `'a'` (the string)
+ * is also valid, which is the default.
+ */
+export type XDSLinkComponentType = ElementType;
diff --git a/packages/core/src/Link/useXDSLinkComponent.test.tsx b/packages/core/src/Link/useXDSLinkComponent.test.tsx
new file mode 100644
index 0000000000..b816f16c67
--- /dev/null
+++ b/packages/core/src/Link/useXDSLinkComponent.test.tsx
@@ -0,0 +1,114 @@
+/**
+ * @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
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {forwardRef, type ComponentPropsWithoutRef} from 'react';
+import {useXDSLinkComponent} from './useXDSLinkComponent';
+import {XDSLinkProvider} from './XDSLinkProvider';
+import type {XDSLinkComponentType} from './types';
+
+// Helper component that renders the resolved link component
+function TestConsumer({as}: {as?: XDSLinkComponentType}) {
+ const LinkComponent = useXDSLinkComponent(as);
+ return (
+ <LinkComponent href="/test" data-testid="resolved-link">
+ Link
+ </LinkComponent>
+ );
+}
+
+const CustomLink = forwardRef<HTMLAnchorElement, ComponentPropsWithoutRef<'a'>>(
+ ({children, ...props}, ref) => (
+ <a ref={ref} data-custom-link {...props}>
+ {children}
+ </a>
+ ),
+);
+CustomLink.displayName = 'CustomLink';
+
+const AnotherLink = forwardRef<
+ HTMLAnchorElement,
+ ComponentPropsWithoutRef<'a'>
+>(({children, ...props}, ref) => (
+ <a ref={ref} data-another-link {...props}>
+ {children}
+ </a>
+));
+AnotherLink.displayName = 'AnotherLink';
+
+// =============================================================================
+// useXDSLinkComponent
+// =============================================================================
+
+describe('useXDSLinkComponent', () => {
+ it('returns native <a> by default (no provider, no as)', () => {
+ render(<TestConsumer />);
+ const link = screen.getByTestId('resolved-link');
+ expect(link.tagName).toBe('A');
+ expect(link).toHaveAttribute('href', '/test');
+ expect(link).not.toHaveAttribute('data-custom-link');
+ });
+
+ it('returns as prop when provided', () => {
+ render(<TestConsumer as={CustomLink} />);
+ const link = screen.getByTestId('resolved-link');
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).toHaveAttribute('href', '/test');
+ });
+
+ it('returns provider component when wrapped in XDSLinkProvider', () => {
+ render(
+ <XDSLinkProvider component={CustomLink}>
+ <TestConsumer />
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByTestId('resolved-link');
+ expect(link).toHaveAttribute('data-custom-link');
+ });
+
+ it('as prop overrides provider', () => {
+ render(
+ <XDSLinkProvider component={AnotherLink}>
+ <TestConsumer as={CustomLink} />
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByTestId('resolved-link');
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).not.toHaveAttribute('data-another-link');
+ });
+});
+
+// =============================================================================
+// XDSLinkProvider
+// =============================================================================
+
+describe('XDSLinkProvider', () => {
+ it('children can access the link component via the hook', () => {
+ render(
+ <XDSLinkProvider component={CustomLink}>
+ <TestConsumer />
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByTestId('resolved-link');
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).toHaveAttribute('href', '/test');
+ });
+
+ it('nested providers — inner overrides outer', () => {
+ render(
+ <XDSLinkProvider component={AnotherLink}>
+ <XDSLinkProvider component={CustomLink}>
+ <TestConsumer />
+ </XDSLinkProvider>
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByTestId('resolved-link');
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).not.toHaveAttribute('data-another-link');
+ });
+});
diff --git a/packages/core/src/Link/useXDSLinkComponent.ts b/packages/core/src/Link/useXDSLinkComponent.ts
new file mode 100644
index 0000000000..40146e4823
--- /dev/null
+++ b/packages/core/src/Link/useXDSLinkComponent.ts
@@ -0,0 +1,41 @@
+/**
+ * @file useXDSLinkComponent.ts
+ * @input React useContext, 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>`.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Link/index.ts
+ * - /packages/core/src/Link/README.md
+ */
+
+'use client';
+
+import {useContext} from 'react';
+import {XDSLinkContext} from './XDSLinkContext';
+import type {XDSLinkComponentType} from './types';
+
+/**
+ * Resolves the link component to use.
+ *
+ * Priority: `as` prop > `XDSLinkProvider` context > native `<a>`.
+ *
+ * @param as - Per-component override. If provided, takes highest priority.
+ * @returns The resolved link component.
+ *
+ * @example
+ * ```tsx
+ * function MyComponent({ as }: { as?: XDSLinkComponentType }) {
+ * const LinkComponent = useXDSLinkComponent(as);
+ * return <LinkComponent href="/foo">Click me</LinkComponent>;
+ * }
+ * ```
+ */
+export function useXDSLinkComponent(
+ as?: XDSLinkComponentType,
+): XDSLinkComponentType {
+ const ctx = useContext(XDSLinkContext);
+ return as ?? ctx?.component ?? 'a';
+}
diff --git a/packages/core/src/SideNav/XDSSideNav.test.tsx b/packages/core/src/SideNav/XDSSideNav.test.tsx
index ed02113041..23c232017a 100644
--- a/packages/core/src/SideNav/XDSSideNav.test.tsx
+++ b/packages/core/src/SideNav/XDSSideNav.test.tsx
@@ -10,10 +10,21 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {forwardRef, type ComponentPropsWithoutRef} from 'react';
import {XDSSideNav} from './XDSSideNav';
import {XDSSideNavHeader} from './XDSSideNavHeader';
import {XDSSideNavItem} from './XDSSideNavItem';
import {XDSSideNavSection} from './XDSSideNavSection';
+import {XDSLinkProvider} from '../Link/XDSLinkProvider';
+
+const CustomLink = forwardRef<HTMLAnchorElement, ComponentPropsWithoutRef<'a'>>(
+ ({children, ...props}, ref) => (
+ <a ref={ref} data-custom-link {...props}>
+ {children}
+ </a>
+ ),
+);
+CustomLink.displayName = 'CustomLink';
// =============================================================================
// XDSSideNav
@@ -288,6 +299,32 @@ describe('XDSSideNavItem', () => {
const link = screen.getByRole('link');
expect(link).toHaveAttribute('aria-current', 'page');
});
+
+ it('renders custom component when as and href are provided', () => {
+ render(
+ <XDSSideNavItem label="Dashboard" href="/dashboard" as={CustomLink} />,
+ );
+ const link = screen.getByRole('link');
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).toHaveAttribute('href', '/dashboard');
+ });
+
+ it('still renders button when no href even with as prop', () => {
+ render(<XDSSideNavItem label="Dashboard" as={CustomLink} />);
+ const button = screen.getByRole('button');
+ expect(button).toBeInTheDocument();
+ expect(button).not.toHaveAttribute('data-custom-link');
+ });
+
+ it('renders custom component from XDSLinkProvider when href is provided', () => {
+ render(
+ <XDSLinkProvider component={CustomLink}>
+ <XDSSideNavItem label="Dashboard" href="/dashboard" />
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByRole('link');
+ expect(link).toHaveAttribute('data-custom-link');
+ });
});
// =============================================================================
diff --git a/packages/core/src/SideNav/XDSSideNavItem.tsx b/packages/core/src/SideNav/XDSSideNavItem.tsx
index c0d74de1d5..b559eb699a 100644
--- a/packages/core/src/SideNav/XDSSideNavItem.tsx
+++ b/packages/core/src/SideNav/XDSSideNavItem.tsx
@@ -27,6 +27,8 @@ import {
} from '../theme/tokens.stylex';
import {XDSIcon} from '../Icon';
import type {XDSIconType} from '../Icon';
+import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+import type {XDSLinkComponentType} from '../Link/types';
// =============================================================================
// Styles
@@ -96,6 +98,12 @@ const styles = stylex.create({
// =============================================================================
export interface XDSSideNavItemProps {
+ /**
+ * Custom component to render instead of `<a>` for link items.
+ * Overrides the provider-level default set by XDSLinkProvider.
+ * Only applies when `href` is provided. Must accept href, className, style, and children props.
+ */
+ as?: XDSLinkComponentType;
/**
* Item label.
*/
@@ -168,6 +176,7 @@ export interface XDSSideNavItemProps {
export const XDSSideNavItem = forwardRef<HTMLElement, XDSSideNavItemProps>(
function XDSSideNavItem(
{
+ as,
label,
icon,
selectedIcon,
@@ -183,6 +192,7 @@ export const XDSSideNavItem = forwardRef<HTMLElement, XDSSideNavItemProps>(
) {
const id = useId();
const hasChildren = !!children;
+ const LinkComponent = useXDSLinkComponent(as);
const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;
@@ -220,7 +230,7 @@ export const XDSSideNavItem = forwardRef<HTMLElement, XDSSideNavItemProps>(
const itemElement =
href && !isDisabled ? (
- <a
+ <LinkComponent
ref={ref as React.Ref<HTMLAnchorElement>}
href={href}
onClick={handleClick}
@@ -231,7 +241,7 @@ export const XDSSideNavItem = forwardRef<HTMLElement, XDSSideNavItemProps>(
isDisabled && styles.disabled,
)}>
{itemContent}
- </a>
+ </LinkComponent>
) : (
<button
ref={ref as React.Ref<HTMLButtonElement>}
diff --git a/packages/core/src/TabList/XDSTab.tsx b/packages/core/src/TabList/XDSTab.tsx
index 24d95452c4..702df3c435 100644
--- a/packages/core/src/TabList/XDSTab.tsx
+++ b/packages/core/src/TabList/XDSTab.tsx
@@ -10,6 +10,8 @@
* - /packages/core/src/TabList/XDSTabList.test.tsx
*/
+'use client';
+
import {useCallback, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
@@ -24,8 +26,16 @@ import {
} from '../theme/tokens.stylex';
import {useXDSTabListContext} from './XDSTabListContext';
import type {XDSTabListSize} from './XDSTabListContext';
+import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+import type {XDSLinkComponentType} from '../Link/types';
export interface XDSTabProps {
+ /**
+ * Custom component to render instead of `<a>` for link tabs.
+ * Overrides the provider-level default set by XDSLinkProvider.
+ * Only applies when `href` is provided. Must accept href, className, style, and children props.
+ */
+ as?: XDSLinkComponentType;
/**
* Unique value for this tab. Matched against XDSTabListContext.value.
*/
@@ -152,8 +162,16 @@ const iconSizeStyles = stylex.create({
* Tab item component. Renders as an anchor when `href` is provided,
* otherwise as a button.
*/
-export function XDSTab({value, label, href, icon, selectedIcon}: XDSTabProps) {
+export function XDSTab({
+ as,
+ value,
+ label,
+ href,
+ icon,
+ selectedIcon,
+}: XDSTabProps) {
const tabListCtx = useXDSTabListContext();
+ const LinkComponent = useXDSLinkComponent(as);
const isSelected = tabListCtx.value === value;
const size: XDSTabListSize = tabListCtx.size;
@@ -195,11 +213,11 @@ export function XDSTab({value, label, href, icon, selectedIcon}: XDSTabProps) {
if (href != null) {
return (
- <a href={href} onClick={handleSelect} {...sharedProps}>
+ <LinkComponent href={href} onClick={handleSelect} {...sharedProps}>
{iconElement}
{labelElement}
{hoverUnderlineElement}
- </a>
+ </LinkComponent>
);
}
diff --git a/packages/core/src/TabList/XDSTabList.test.tsx b/packages/core/src/TabList/XDSTabList.test.tsx
index ee5092f077..b06f085beb 100644
--- a/packages/core/src/TabList/XDSTabList.test.tsx
+++ b/packages/core/src/TabList/XDSTabList.test.tsx
@@ -10,9 +10,20 @@
import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {forwardRef, type ComponentPropsWithoutRef} from 'react';
import {XDSTabList} from './XDSTabList';
import {XDSTab} from './XDSTab';
import {XDSTabMenu} from './XDSTabMenu';
+import {XDSLinkProvider} from '../Link/XDSLinkProvider';
+
+const CustomLink = forwardRef<HTMLAnchorElement, ComponentPropsWithoutRef<'a'>>(
+ ({children, ...props}, ref) => (
+ <a ref={ref} data-custom-link {...props}>
+ {children}
+ </a>
+ ),
+);
+CustomLink.displayName = 'CustomLink';
// Store original matches to restore later
const originalMatches = HTMLElement.prototype.matches;
@@ -180,6 +191,42 @@ describe('XDSTabList', () => {
});
});
+describe('XDSTab polymorphic link', () => {
+ it('renders custom component when href and as are provided', () => {
+ render(
+ <XDSTabList value="home" onChange={() => {}}>
+ <XDSTab value="home" label="Home" href="/home" as={CustomLink} />
+ </XDSTabList>,
+ );
+ const link = screen.getByRole('link', {name: 'Home'});
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).toHaveAttribute('href', '/home');
+ });
+
+ it('still renders button without href even with as prop', () => {
+ render(
+ <XDSTabList value="home" onChange={() => {}}>
+ <XDSTab value="home" label="Home" as={CustomLink} />
+ </XDSTabList>,
+ );
+ const button = screen.getByRole('button', {name: 'Home'});
+ expect(button).toBeInTheDocument();
+ expect(button).not.toHaveAttribute('data-custom-link');
+ });
+
+ it('renders custom component from XDSLinkProvider when href is provided', () => {
+ render(
+ <XDSLinkProvider component={CustomLink}>
+ <XDSTabList value="home" onChange={() => {}}>
+ <XDSTab value="home" label="Home" href="/home" />
+ </XDSTabList>
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByRole('link', {name: 'Home'});
+ expect(link).toHaveAttribute('data-custom-link');
+ });
+});
+
describe('XDSTabMenu', () => {
const menuOptions = [
{value: 'analytics', label: 'Analytics'},
diff --git a/packages/core/src/TopNav/XDSTopNav.test.tsx b/packages/core/src/TopNav/XDSTopNav.test.tsx
index 3798839f89..aeb255f06f 100644
--- a/packages/core/src/TopNav/XDSTopNav.test.tsx
+++ b/packages/core/src/TopNav/XDSTopNav.test.tsx
@@ -10,10 +10,21 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import {forwardRef, type ComponentPropsWithoutRef} from 'react';
import {XDSTopNav} from './XDSTopNav';
import {XDSTopNavTitle} from './XDSTopNavTitle';
import {XDSNavIcon} from '../NavIcon';
import {XDSTopNavItem} from './XDSTopNavItem';
+import {XDSLinkProvider} from '../Link/XDSLinkProvider';
+
+const CustomLink = forwardRef<HTMLAnchorElement, ComponentPropsWithoutRef<'a'>>(
+ ({children, ...props}, ref) => (
+ <a ref={ref} data-custom-link {...props}>
+ {children}
+ </a>
+ ),
+);
+CustomLink.displayName = 'CustomLink';
describe('XDSTopNav', () => {
it('renders with navigation role', () => {
@@ -241,4 +252,40 @@ describe('XDSTopNavItem', () => {
render(<XDSTopNavItem label="Test" ref={ref} />);
expect(ref).toHaveBeenCalledWith(expect.any(HTMLAnchorElement));
});
+
+ it('renders custom component when as is provided', () => {
+ render(<XDSTopNavItem label="Home" href="/" as={CustomLink} />);
+ const link = screen.getByRole('link', {name: 'Home'});
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).toHaveAttribute('href', '/');
+ });
+
+ it('renders custom component from XDSLinkProvider', () => {
+ render(
+ <XDSLinkProvider component={CustomLink}>
+ <XDSTopNavItem label="Home" href="/" />
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByRole('link', {name: 'Home'});
+ expect(link).toHaveAttribute('data-custom-link');
+ });
+
+ it('as prop overrides XDSLinkProvider', () => {
+ const AnotherLink = forwardRef<
+ HTMLAnchorElement,
+ ComponentPropsWithoutRef<'a'>
+ >(({children, ...props}, ref) => (
+ <a ref={ref} data-another-link {...props}>
+ {children}
+ </a>
+ ));
+ render(
+ <XDSLinkProvider component={AnotherLink}>
+ <XDSTopNavItem label="Home" href="/" as={CustomLink} />
+ </XDSLinkProvider>,
+ );
+ const link = screen.getByRole('link', {name: 'Home'});
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link).not.toHaveAttribute('data-another-link');
+ });
});
diff --git a/packages/core/src/TopNav/XDSTopNavItem.tsx b/packages/core/src/TopNav/XDSTopNavItem.tsx
index 2d3b202e29..b0bc2bf87f 100644
--- a/packages/core/src/TopNav/XDSTopNavItem.tsx
+++ b/packages/core/src/TopNav/XDSTopNavItem.tsx
@@ -11,6 +11,8 @@
* - /apps/storybook/stories/TopNav.stories.tsx
*/
+'use client';
+
import {forwardRef, type AnchorHTMLAttributes, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
@@ -22,6 +24,8 @@ import {
fontWeightVars,
lineHeightVars,
} from '../theme/tokens.stylex';
+import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+import type {XDSLinkComponentType} from '../Link/types';
/**
* NavItem styles with hover/selected states
@@ -79,6 +83,12 @@ export interface XDSTopNavItemProps extends Omit<
AnchorHTMLAttributes<HTMLAnchorElement>,
'style' | 'className'
> {
+ /**
+ * Custom component to render instead of `<a>`.
+ * Overrides the provider-level default set by XDSLinkProvider.
+ * Must accept href, className, style, and children props.
+ */
+ as?: XDSLinkComponentType;
/**
* The accessible label for the nav item.
* Used as visible text, or as aria-label for icon-only items.
@@ -127,14 +137,23 @@ export interface XDSTopNavItemProps extends Omit<
*/
export const XDSTopNavItem = forwardRef<HTMLAnchorElement, XDSTopNavItemProps>(
function XDSTopNavItem(
- {label, isSelected = false, isDisabled = false, icon, children, ...props},
+ {
+ as,
+ label,
+ isSelected = false,
+ isDisabled = false,
+ icon,
+ children,
+ ...props
+ },
ref,
) {
+ const LinkComponent = useXDSLinkComponent(as);
const isIconOnly = icon != null && children == null && !label;
const showLabel = !isIconOnly;
return (
- <a
+ <LinkComponent
ref={ref}
aria-label={isIconOnly ? label : undefined}
aria-current={isSelected ? 'page' : undefined}
@@ -149,7 +168,7 @@ export const XDSTopNavItem = forwardRef<HTMLAnchorElement, XDSTopNavItemProps>(
{...props}>
{icon}
{showLabel && (children ?? label)}
- </a>
+ </LinkComponent>
);
},
);