Improve Link component to add title

Signed-off-by: Charles de Dreuille <charles.dedreuille@gmail.com>
This commit is contained in:
Charles de Dreuille
2025-11-30 09:01:03 +00:00
parent c353de0b9b
commit 8bd2335b95
2 changed files with 49 additions and 14 deletions
+42 -14
View File
@@ -14,8 +14,9 @@
* limitations under the License.
*/
import { forwardRef } from 'react';
import { Link as AriaLink, RouterProvider } from 'react-aria-components';
import { forwardRef, useRef } from 'react';
import { useLink } from 'react-aria';
import { RouterProvider } from 'react-aria-components';
import clsx from 'clsx';
import { useStyles } from '../../hooks/useStyles';
import { LinkDefinition } from './definition';
@@ -37,29 +38,56 @@ export const Link = forwardRef<HTMLAnchorElement, LinkProps>((props, ref) => {
},
);
const { className, href, ...restProps } = cleanedProps;
const {
className,
href,
title,
children,
onPress,
variant,
weight,
color,
truncate,
slot,
...restProps
} = cleanedProps;
const isExternal = isExternalLink(href);
const internalRef = useRef<HTMLAnchorElement>(null);
const linkRef = (ref || internalRef) as React.RefObject<HTMLAnchorElement>;
const component = (
<AriaLink
ref={ref}
className={clsx(classNames.root, styles[classNames.root], className)}
href={href}
{...dataAttributes}
{...restProps}
/>
// Use useLink hook to get link props
const { linkProps } = useLink(
{
href,
onPress,
...restProps,
},
linkRef,
);
// If it's an external link, render AriaLink without RouterProvider
const anchorElement = (
<a
{...linkProps}
{...dataAttributes}
ref={linkRef}
href={href}
title={title}
className={clsx(classNames.root, styles[classNames.root], className)}
>
{children}
</a>
);
// If it's an external link, render without RouterProvider
if (isExternal) {
return component;
return anchorElement;
}
// For internal links, use RouterProvider
return (
<RouterProvider navigate={navigate} useHref={useHref}>
{component}
{anchorElement}
</RouterProvider>
);
});
+7
View File
@@ -22,6 +22,7 @@ import type {
TextWeights,
} from '../../types';
import type { LinkProps as AriaLinkProps } from 'react-aria-components';
import type { ReactNode } from 'react';
/** @public */
export interface LinkProps extends AriaLinkProps {
@@ -32,4 +33,10 @@ export interface LinkProps extends AriaLinkProps {
| TextColorStatus
| Partial<Record<Breakpoint, TextColors | TextColorStatus>>;
truncate?: boolean;
// This is used to set the title attribute on the link
title?: string;
// This is used to set the children of the link
children?: ReactNode;
}