Skip to content

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

TypeScript

refactor(core): extract mergeRefs utility and replace 36 hand-rolled callsites (#2314)

Andrey Goder427b975e235d
diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsx
index 3347315311..978cb4b8c5 100644
--- a/packages/core/src/AppShell/XDSAppShell.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.tsx
@@ -50,7 +50,7 @@ import {useXDSSlotPresence} from './useXDSSlotPresence';
import type {XDSAppShellMobileContextValue} from './XDSAppShellMobileContext';
import type {SpacingStep} from '../utils/types';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {useMediaQuery} from '../hooks/useMediaQuery';
import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
@@ -546,19 +546,6 @@ export function XDSAppShell({
const headerRef = useRef<HTMLDivElement>(null);
const shellRef = useRef<HTMLDivElement>(null);
- // Merge forwarded ref with internal shell ref
- const setShellRef = useCallback(
- (node: HTMLDivElement | null) => {
- (shellRef as React.RefObject<HTMLDivElement | null>).current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref) {
- (ref as React.RefObject<HTMLDivElement | null>).current = node;
- }
- },
- [ref],
- );
-
useEffect(() => {
if (!isAuto || !headerRef.current || !shellRef.current) {
return;
@@ -777,7 +764,7 @@ export function XDSAppShell({
return (
<XDSAppShellMobileContext value={mobileContextValue}>
<div
- ref={setShellRef}
+ ref={mergeRefs(ref, shellRef)}
data-testid={dataTestId}
{...mergeProps(
xdsClassName('app-shell', {variant}),
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
index eef4a20a0c..26c7269d4a 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
@@ -28,7 +28,7 @@ import {colorVars, spacingVars, typeScaleVars} from '../theme/tokens.stylex';
import {BreadcrumbContext} from './XDSBreadcrumbs';
import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
import type {XDSLinkComponentType} from '../Link/types';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
// =============================================================================
@@ -181,16 +181,6 @@ export function XDSBreadcrumbItem({
const isSupporting = ctx.variant === 'supporting';
const liRef = useRef<HTMLLIElement>(null);
- // Merge refs
- const setLiRef = (element: HTMLLIElement | null) => {
- (liRef as React.RefObject<HTMLLIElement | null>).current = element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- (ref as React.RefObject<HTMLLIElement | null>).current = element;
- }
- };
-
const isCurrent = isCurrentProp === true;
const isAutoCandidate = isCurrentProp == null;
@@ -235,7 +225,7 @@ export function XDSBreadcrumbItem({
if (isCurrent) {
return (
<li
- ref={setLiRef}
+ ref={mergeRefs(ref, liRef)}
{...mergeProps(
xdsClassName('breadcrumb-item'),
stylex.props(
@@ -266,7 +256,7 @@ export function XDSBreadcrumbItem({
// The effect handles adding aria-current for auto-last detection.
return (
<li
- ref={setLiRef}
+ ref={mergeRefs(ref, liRef)}
{...mergeProps(
xdsClassName('breadcrumb-item'),
stylex.props(
diff --git a/packages/core/src/ButtonGroup/XDSButtonGroup.tsx b/packages/core/src/ButtonGroup/XDSButtonGroup.tsx
index fe5952d498..1b60052514 100644
--- a/packages/core/src/ButtonGroup/XDSButtonGroup.tsx
+++ b/packages/core/src/ButtonGroup/XDSButtonGroup.tsx
@@ -25,7 +25,7 @@ import * as stylex from '@stylexjs/stylex';
import type {XDSButtonSize} from '../Button';
import {XDSSizeProvider, useXDSSize} from '../SizeContext/XDSSizeContext';
import {useListFocus} from '../hooks/useListFocus';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {XDSButtonGroupContext} from './XDSButtonGroupContext';
import type {XDSButtonGroupOrientation} from './XDSButtonGroupContext';
@@ -122,7 +122,7 @@ export function XDSButtonGroup({
}: XDSButtonGroupProps): ReactNode {
const size = useXDSSize(sizeProp, 'md');
- const {listRef, handleKeyDown} = useListFocus({
+ const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({
itemSelector: 'button, [tabindex="0"]',
orientation,
});
@@ -136,15 +136,7 @@ export function XDSButtonGroup({
<XDSButtonGroupContext value={contextValue}>
<XDSSizeProvider value={size}>
<div
- ref={(node: HTMLDivElement | null) => {
- // eslint-disable-next-line react-compiler/react-compiler -- ref callback: assigning hook-returned ref
- listRef.current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref) {
- ref.current = node;
- }
- }}
+ ref={mergeRefs(ref, listRef)}
role="group"
aria-label={label}
onKeyDown={handleKeyDown}
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
index 45644f0cae..b0f9f45e1c 100644
--- a/packages/core/src/Calendar/XDSCalendar.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -595,14 +595,15 @@ function MonthGrid({
}, [getFocusedDate, onNavigateNext]);
// Grid focus navigation
- const {gridRef, handleKeyDown: handleGridKeyDown} = useGridFocus({
- columns: 7,
- cellSelector: 'button:not([disabled])',
- onNavigateBefore: handleNavigatePrevious,
- onNavigateAfter: handleNavigateNext,
- onPageUp: handlePageUp,
- onPageDown: handlePageDown,
- });
+ const {gridRef, handleKeyDown: handleGridKeyDown} =
+ useGridFocus<HTMLDivElement>({
+ columns: 7,
+ cellSelector: 'button:not([disabled])',
+ onNavigateBefore: handleNavigatePrevious,
+ onNavigateAfter: handleNavigateNext,
+ onPageUp: handlePageUp,
+ onPageDown: handlePageDown,
+ });
// Handle pending focus after month navigation
useEffect(() => {
@@ -702,7 +703,7 @@ function MonthGrid({
{/* Days grid */}
<div
- ref={gridRef as React.RefObject<HTMLDivElement | null>}
+ ref={gridRef}
role="grid"
aria-label={monthLabel}
onKeyDown={handleGridKeyDown}
diff --git a/packages/core/src/Carousel/XDSCarousel.tsx b/packages/core/src/Carousel/XDSCarousel.tsx
index a98696f11d..7df99b9a34 100644
--- a/packages/core/src/Carousel/XDSCarousel.tsx
+++ b/packages/core/src/Carousel/XDSCarousel.tsx
@@ -31,7 +31,7 @@ import {XDSIcon} from '../Icon';
import {useXDSLayer} from '../Layer';
import {useScrollOverflow} from '../hooks/useScrollOverflow';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
export interface XDSCarouselProps extends XDSBaseProps<HTMLDivElement> {
ref?: React.Ref<HTMLDivElement>;
@@ -274,16 +274,7 @@ export function XDSCarousel({
return (
<div
- ref={(el: HTMLDivElement | null) => {
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- if (layer.ref) {
- layer.ref(el as HTMLElement | null);
- }
- }}
+ ref={mergeRefs(ref, layer.ref as React.Ref<HTMLDivElement>)}
data-testid={testId}
role="region"
aria-label={ariaLabel}
diff --git a/packages/core/src/Chat/XDSChatLayout.tsx b/packages/core/src/Chat/XDSChatLayout.tsx
index 9e08e522ad..ae315dc4b0 100644
--- a/packages/core/src/Chat/XDSChatLayout.tsx
+++ b/packages/core/src/Chat/XDSChatLayout.tsx
@@ -18,18 +18,11 @@
* - /packages/cli/templates/blocks/components/ChatLayout/ (block examples)
*/
-import {
- type ReactNode,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from 'react';
+import {type ReactNode, useEffect, useMemo, useRef, useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars} from '../theme/tokens.stylex';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
import {useXDSChatStreamScroll} from './useXDSChatStreamScroll';
import {useXDSChatNewMessages} from './useXDSChatNewMessages';
@@ -263,8 +256,7 @@ export function XDSChatLayout({
}: XDSChatLayoutProps) {
const rootRef = useRef<HTMLDivElement>(null);
- const scrollContainerRef =
- externalScrollRef ?? (rootRef as React.RefObject<HTMLElement | null>);
+ const scrollContainerRef = externalScrollRef ?? rootRef;
const isSelfScrolling = !externalScrollRef;
const [density, setDensity] = useState<Density>('balanced');
@@ -305,19 +297,6 @@ export function XDSChatLayout({
return () => unobserveResize(root);
}, []);
- // --- Merge refs ---
- const setRootRef = useCallback(
- (el: HTMLDivElement | null) => {
- rootRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
// --- Derived styles ---
const showEmpty = !hasVisibleContent(children);
@@ -352,7 +331,7 @@ export function XDSChatLayout({
return (
<XDSChatLayoutContext value={layoutContext}>
<div
- ref={setRootRef}
+ ref={mergeRefs(ref, rootRef)}
data-testid={testId}
data-density={density}
{...mergeProps(
diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
index 4e25e85538..c0a578f126 100644
--- a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
@@ -43,7 +43,7 @@ import {XDSFieldStatus} from '../Field/XDSFieldStatus';
import type {XDSIconType} from '../Icon';
import type {XDSInputStatus} from '../Field/types';
import {XDSSpinner} from '../Spinner';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {checkboxScope} from './checkbox.markers.stylex';
const styles = stylex.create({
@@ -362,13 +362,8 @@ export function XDSCheckboxInput({
if (el) {
el.indeterminate = isIndeterminate;
}
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
},
- [isIndeterminate, ref],
+ [isIndeterminate],
);
// Build aria-describedby from description and status message
@@ -399,7 +394,7 @@ export function XDSCheckboxInput({
)}>
<div {...stylex.props(styles.checkboxWrapper, wrapperSizeStyles[size])}>
<input
- ref={indeterminateRef}
+ ref={mergeRefs(ref, indeterminateRef)}
id={id}
type="checkbox"
checked={isChecked}
diff --git a/packages/core/src/ClickableCard/XDSClickableCard.tsx b/packages/core/src/ClickableCard/XDSClickableCard.tsx
index 5efc5b0336..dd966e49b0 100644
--- a/packages/core/src/ClickableCard/XDSClickableCard.tsx
+++ b/packages/core/src/ClickableCard/XDSClickableCard.tsx
@@ -33,7 +33,7 @@ import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
import type {SizeValue, SpacingStep} from '../utils/types';
-import {xdsClassName} from '../utils';
+import {xdsClassName, mergeRefs} from '../utils';
import {XDSCard} from '../Card/XDSCard';
import type {XDSCardVariant} from '../Card/XDSCard';
import {useClickableContainer} from '../hooks/useClickableContainer';
@@ -247,14 +247,7 @@ export function XDSClickableCard({
return (
<XDSCard
- ref={(node: HTMLDivElement | null) => {
- containerRef.current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref != null) {
- ref.current = node;
- }
- }}
+ ref={mergeRefs(ref, containerRef)}
width={width}
height={height}
maxWidth={maxWidth}
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
index 0584c3f4b4..78063a6dcd 100644
--- a/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
@@ -16,7 +16,7 @@ import {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {XDSIcon} from '../Icon';
import {XDSSpinner} from '../Spinner';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {
colorVars,
typeScaleVars,
@@ -165,16 +165,6 @@ export function XDSCommandPaletteInput({
// to avoid stealing focus from the surrounding page.
const effectiveAutoFocus = hasAutoFocus && !(ctx?.isInline ?? false);
- // Merge refs
- const setRefs = (element: HTMLInputElement | null) => {
- inputRef.current = element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- };
-
// Auto-focus on mount
useEffect(() => {
if (effectiveAutoFocus && inputRef.current) {
@@ -207,7 +197,7 @@ export function XDSCommandPaletteInput({
<XDSIcon icon="search" size="sm" color="inherit" />
</span>
<input
- ref={setRefs}
+ ref={mergeRefs(ref, inputRef)}
type="text"
role="combobox"
aria-expanded={ctx?.isOpen ?? true}
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
index cc7736d0e8..84b8fce84f 100644
--- a/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
@@ -14,7 +14,7 @@
import {useCallback, useEffect, useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {
colorVars,
spacingVars,
@@ -130,15 +130,6 @@ export function XDSCommandPaletteItem({
const ctx = useCommandPaletteContext();
const itemRef = useRef<HTMLDivElement>(null);
- const setRefs = (element: HTMLDivElement | null) => {
- itemRef.current = element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- };
-
// Find this item's index in the flat selectable items list (DOM order).
// This aligns with useCombobox's index-based navigation.
const itemIndex = useMemo(
@@ -178,7 +169,7 @@ export function XDSCommandPaletteItem({
return (
<div
- ref={setRefs}
+ ref={mergeRefs(ref, itemRef)}
id={ctx && itemIndex >= 0 ? ctx.getItemId(itemIndex) : undefined}
role="option"
aria-selected={isSelected}
diff --git a/packages/core/src/ContextMenu/XDSContextMenu.tsx b/packages/core/src/ContextMenu/XDSContextMenu.tsx
index d1a7c0b5eb..4cef346af4 100644
--- a/packages/core/src/ContextMenu/XDSContextMenu.tsx
+++ b/packages/core/src/ContextMenu/XDSContextMenu.tsx
@@ -211,7 +211,7 @@ export function XDSContextMenu({
listRef,
handleKeyDown: listNavKeyDown,
focusFirst,
- } = useListFocus({
+ } = useListFocus<HTMLDivElement>({
itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',
wrap: false,
onEscape: closeMenu,
@@ -287,7 +287,7 @@ export function XDSContextMenu({
{layer.render(
<div
- ref={listRef as React.RefObject<HTMLDivElement>}
+ ref={listRef}
id={menuId}
role="menu"
onKeyDown={listKeyDown}
diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
index af0a7fe1ac..07915ea093 100644
--- a/packages/core/src/DateInput/XDSDateInput.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -132,7 +132,7 @@ export type {
XDSInputStatus as XDSDateInputStatus,
XDSInputStatusType as XDSDateInputStatusType,
} from '../Field';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {XDSBaseProps} from '../XDSBaseProps';
export interface XDSDateInputProps extends Omit<
@@ -482,19 +482,6 @@ export function XDSDateInput({
[popover, commitPendingInput],
);
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
return (
<XDSField
label={label}
@@ -544,7 +531,7 @@ export function XDSDateInput({
<XDSIcon icon="calendar" size="sm" color="secondary" />
</button>
<input
- ref={setRefs}
+ ref={mergeRefs(ref, inputRef)}
id={id}
type="text"
role="combobox"
diff --git a/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx b/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
index 984ef34b2a..981b543c6f 100644
--- a/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/XDSDateTimeInput.tsx
@@ -67,6 +67,7 @@ import {
adjustTime,
xdsClassName,
mergeProps,
+ mergeRefs,
} from '../utils';
import {
plainDateFromISO,
@@ -743,19 +744,6 @@ export function XDSDateTimeInput({
dateInputRef.current?.focus();
}, [fireChange]);
- // --- Refs ---
- const setDateRefs = useCallback(
- (el: HTMLInputElement | null) => {
- dateInputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
// Focus time input when clicking wrapper padding/icon
const {onClick: handleTimeWrapperClick, onMouseUp: handleTimeWrapperMouseUp} =
useInputContainer({
@@ -820,7 +808,7 @@ export function XDSDateTimeInput({
<XDSIcon icon="calendar" size="sm" color="secondary" />
</button>
<input
- ref={setDateRefs}
+ ref={mergeRefs(ref, dateInputRef)}
id={dateInputId}
type="text"
role="combobox"
diff --git a/packages/core/src/Dialog/XDSDialog.tsx b/packages/core/src/Dialog/XDSDialog.tsx
index 8477515a5a..4e7eb4511f 100644
--- a/packages/core/src/Dialog/XDSDialog.tsx
+++ b/packages/core/src/Dialog/XDSDialog.tsx
@@ -37,7 +37,7 @@ import {
spacingStepToToken,
} from '../Layout/padding.stylex';
import type {SpacingStep} from '../utils/types';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
/**
* Calculate a directional translate offset for dialog entry animation.
@@ -355,16 +355,6 @@ export function XDSDialog({
const allowEscape = purpose !== 'required';
const allowBackdropClick = purpose === 'info';
- // Merge refs
- const setRefs = (element: HTMLDialogElement | null) => {
- dialogRef.current = element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- };
-
// Handle open/close state — skip for inline rendering
useEffect(() => {
if (isInline) {
@@ -539,7 +529,7 @@ export function XDSDialog({
return (
<dialog
- ref={setRefs}
+ ref={mergeRefs(ref, dialogRef)}
onClick={handleClick}
onCancel={handleCancel}
aria-modal="true"
diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx
index 8f9c29461d..299d1b13f0 100644
--- a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx
@@ -264,7 +264,7 @@ export function XDSDropdownMenu({
listRef,
handleKeyDown: listNavKeyDown,
focusFirst,
- } = useListFocus({
+ } = useListFocus<HTMLDivElement>({
itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',
wrap: false,
onEscape: closeMenu,
@@ -396,7 +396,7 @@ export function XDSDropdownMenu({
{popover.render(
<div
- ref={listRef as React.RefObject<HTMLDivElement>}
+ ref={listRef}
id={menuId}
role="menu"
onKeyDown={listKeyDown}
@@ -413,7 +413,11 @@ export function XDSDropdownMenu({
{
placement: 'below',
alignment: 'start',
- xstyle: [popoverXstyle, popoverOverlayStyles[menuSize], layerAnimations.below],
+ xstyle: [
+ popoverXstyle,
+ popoverOverlayStyles[menuSize],
+ layerAnimations.below,
+ ],
},
)}
</>
diff --git a/packages/core/src/FileInput/XDSFileInput.tsx b/packages/core/src/FileInput/XDSFileInput.tsx
index 35508b3b6d..f024f94d2e 100644
--- a/packages/core/src/FileInput/XDSFileInput.tsx
+++ b/packages/core/src/FileInput/XDSFileInput.tsx
@@ -44,7 +44,7 @@ export type {
XDSInputStatus as XDSFileInputStatus,
XDSInputStatusType as XDSFileInputStatusType,
} from '../Field';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {XDSBaseProps} from '../XDSBaseProps';
function formatFileSize(bytes: number): string {
@@ -576,18 +576,6 @@ export function XDSFileInput({
[isDisabled, mode, handleFiles],
);
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
const hasFiles =
value != null && (Array.isArray(value) ? value.length > 0 : true);
const fileNames = hasFiles
@@ -704,7 +692,7 @@ export function XDSFileInput({
)}>
<input
{...rest}
- ref={setRefs}
+ ref={mergeRefs(ref, inputRef)}
id={id}
type="file"
accept={accept}
diff --git a/packages/core/src/HoverCard/XDSHoverCard.tsx b/packages/core/src/HoverCard/XDSHoverCard.tsx
index 7d3204df1c..a833bfbd4f 100644
--- a/packages/core/src/HoverCard/XDSHoverCard.tsx
+++ b/packages/core/src/HoverCard/XDSHoverCard.tsx
@@ -172,7 +172,7 @@ export function XDSHoverCard({
isOpen,
isDefaultOpen,
}: XDSHoverCardProps): ReactElement {
- const wrapperRef = useRef<HTMLElement>(null);
+ const wrapperRef = useRef<HTMLDivElement>(null);
const textOnly = isTextOnly(children);
// Determine if hover indication should be shown
@@ -259,9 +259,7 @@ export function XDSHoverCard({
// For element children: use display:contents, ref on first child
return (
<>
- <div
- ref={wrapperRef as React.RefObject<HTMLDivElement | null>}
- {...stylex.props(styles.wrapperContents)}>
+ <div ref={wrapperRef} {...stylex.props(styles.wrapperContents)}>
{children}
</div>
{hoverCard.renderHoverCard(content)}
diff --git a/packages/core/src/MobileNav/XDSMobileNav.tsx b/packages/core/src/MobileNav/XDSMobileNav.tsx
index 24a64c676c..080130c812 100644
--- a/packages/core/src/MobileNav/XDSMobileNav.tsx
+++ b/packages/core/src/MobileNav/XDSMobileNav.tsx
@@ -46,7 +46,7 @@ import {XDSButton} from '../Button';
import {XDSIcon} from '../Icon';
import {XDSHeading} from '../Text/XDSHeading';
import {useXDSAppShellMobile} from '../AppShell/XDSAppShellMobileContext';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {XDSBaseProps} from '../XDSBaseProps';
// =============================================================================
@@ -310,19 +310,6 @@ export function XDSMobileNav({
side === 'auto' ? 'end' : side,
);
- // Merge refs
- const setRefs = useCallback(
- (element: HTMLDialogElement | null) => {
- dialogRef.current = element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- },
- [ref],
- );
-
// Open/close the dialog via showModal()/close()
// close() is delayed so the slide-out transition can play.
useEffect(() => {
@@ -403,7 +390,7 @@ export function XDSMobileNav({
return (
<dialog
- ref={setRefs}
+ ref={mergeRefs(ref, dialogRef)}
data-testid={testId}
aria-label={label ?? (typeof header === 'string' ? header : 'Navigation')}
onClick={handleDialogClick}
diff --git a/packages/core/src/NumberInput/XDSNumberInput.tsx b/packages/core/src/NumberInput/XDSNumberInput.tsx
index 17b96f64a0..c6e5bc16e3 100644
--- a/packages/core/src/NumberInput/XDSNumberInput.tsx
+++ b/packages/core/src/NumberInput/XDSNumberInput.tsx
@@ -128,7 +128,7 @@ export type {
XDSInputStatus as XDSNumberInputStatus,
XDSInputStatusType as XDSNumberInputStatusType,
} from '../Field';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {XDSBaseProps} from '../XDSBaseProps';
interface XDSNumberInputPropsBase extends Omit<
@@ -494,19 +494,6 @@ export function XDSNumberInput({
],
);
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
// Handle clear button click
const handleClear = useCallback(() => {
if (hasClear) {
@@ -548,7 +535,7 @@ export function XDSNumberInput({
{startIcon && renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
<input
{...rest}
- ref={setRefs}
+ ref={mergeRefs(ref, inputRef)}
id={id}
name={htmlName}
type="number"
diff --git a/packages/core/src/OverflowList/XDSOverflowList.tsx b/packages/core/src/OverflowList/XDSOverflowList.tsx
index b859774ef2..29d80ca5e3 100644
--- a/packages/core/src/OverflowList/XDSOverflowList.tsx
+++ b/packages/core/src/OverflowList/XDSOverflowList.tsx
@@ -21,7 +21,7 @@ import {type ReactNode, type ReactElement, Children} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import type {SpacingStep} from '../utils/types';
import * as stylex from '@stylexjs/stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {useOverflow} from '../hooks/useOverflow';
import {spacingVars} from '../theme/tokens.stylex';
@@ -243,14 +243,7 @@ export function XDSOverflowList({
{/* Visible container */}
<div
- ref={el => {
- containerRef(el);
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- }}
+ ref={mergeRefs(ref, containerRef)}
{...mergeProps(
xdsClassName('overflow-list'),
stylex.props(
diff --git a/packages/core/src/Overlay/XDSOverlay.tsx b/packages/core/src/Overlay/XDSOverlay.tsx
index 45f9a85909..0fb6078355 100644
--- a/packages/core/src/Overlay/XDSOverlay.tsx
+++ b/packages/core/src/Overlay/XDSOverlay.tsx
@@ -18,7 +18,7 @@
import {type ReactNode, type Ref} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {useXDSOverlay} from './useXDSOverlay';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {overlayScope, overlayContainerStyles} from './overlay.markers.stylex';
@@ -124,14 +124,7 @@ export function XDSOverlay({
return (
<div
- ref={(node: HTMLDivElement | null) => {
- overlay.containerRef.current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref != null) {
- ref.current = node;
- }
- }}
+ ref={mergeRefs(ref, overlay.containerRef)}
{...mergeProps(
xdsClassName('overlay'),
stylex.props(overlayScope, overlayContainerStyles.root, xstyle),
diff --git a/packages/core/src/Popover/useXDSPopover.tsx b/packages/core/src/Popover/useXDSPopover.tsx
index dd8c3382cf..a41ebe9e59 100644
--- a/packages/core/src/Popover/useXDSPopover.tsx
+++ b/packages/core/src/Popover/useXDSPopover.tsx
@@ -162,7 +162,7 @@ export interface UseXDSPopoverReturn {
* You typically don't need to use this directly - the render function
* automatically wraps content in a focus trap container.
*/
- contentRef: React.RefObject<HTMLElement | null>;
+ contentRef: React.RefObject<HTMLDivElement | null>;
/**
* The CSS anchor name to use for positioning.
@@ -291,7 +291,7 @@ export function useXDSPopover(
});
// Focus trap for the popover content
- const {containerRef: contentRef, focusFirst} = useFocusTrap({
+ const {containerRef: contentRef, focusFirst} = useFocusTrap<HTMLDivElement>({
isActive: layer.isOpen,
onEscape: layer.hide,
});
@@ -349,7 +349,7 @@ export function useXDSPopover(
(children: ReactNode, props?: ContextRenderProps) => {
return layer.render(
<div
- ref={contentRef as React.RefObject<HTMLDivElement | null>}
+ ref={contentRef}
role="dialog"
aria-modal="true"
aria-label={dialogLabel}
diff --git a/packages/core/src/Resizable/XDSResizeHandle.tsx b/packages/core/src/Resizable/XDSResizeHandle.tsx
index a12dc22463..eeccd7033c 100644
--- a/packages/core/src/Resizable/XDSResizeHandle.tsx
+++ b/packages/core/src/Resizable/XDSResizeHandle.tsx
@@ -30,7 +30,7 @@ import {
radiusVars,
spacingVars,
} from '../theme/tokens.stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {ResizableProps} from './useXDSResizable';
const KEYBOARD_STEP = 10;
@@ -471,14 +471,7 @@ export function XDSResizeHandle({
return (
<div
- ref={node => {
- handleRef.current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref) {
- ref.current = node;
- }
- }}
+ ref={mergeRefs(ref, handleRef)}
role="separator"
aria-orientation={isHorizontal ? 'vertical' : 'horizontal'}
aria-valuenow={ariaValueNow}
diff --git a/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx b/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
index b3244a2837..ec1d774cbe 100644
--- a/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
+++ b/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
@@ -23,7 +23,7 @@ import type {
XDSSegmentedControlSize,
XDSSegmentedControlLayout,
} from './XDSSegmentedControlContext';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {useXDSSize} from '../SizeContext/XDSSizeContext';
import type {XDSBaseProps} from '../XDSBaseProps';
@@ -134,16 +134,6 @@ export function XDSSegmentedControl({
const size = useXDSSize(sizeProp, 'md') as XDSSegmentedControlSize;
const containerRef = useRef<HTMLDivElement>(null);
- // Merge refs
- const setContainerRef = (element: HTMLDivElement | null) => {
- (containerRef as React.RefObject<HTMLDivElement | null>).current = element;
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- (ref as React.RefObject<HTMLDivElement | null>).current = element;
- }
- };
-
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (isDisabled) {
@@ -209,7 +199,7 @@ export function XDSSegmentedControl({
return (
<XDSSegmentedControlContext value={contextValue}>
<div
- ref={setContainerRef}
+ ref={mergeRefs(ref, containerRef)}
role="radiogroup"
aria-label={label}
aria-disabled={isDisabled || undefined}
diff --git a/packages/core/src/SelectableCard/XDSSelectableCard.tsx b/packages/core/src/SelectableCard/XDSSelectableCard.tsx
index a2a7e50344..21100ee208 100644
--- a/packages/core/src/SelectableCard/XDSSelectableCard.tsx
+++ b/packages/core/src/SelectableCard/XDSSelectableCard.tsx
@@ -37,7 +37,7 @@ import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
import type {SizeValue, SpacingStep} from '../utils/types';
-import {xdsClassName} from '../utils';
+import {xdsClassName, mergeRefs} from '../utils';
import {XDSCard} from '../Card/XDSCard';
import type {XDSCardVariant} from '../Card/XDSCard';
import {useClickableContainer} from '../hooks/useClickableContainer';
@@ -315,14 +315,7 @@ export function XDSSelectableCard({
return (
<XDSCard
- ref={(node: HTMLDivElement | null) => {
- containerRef.current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref != null) {
- ref.current = node;
- }
- }}
+ ref={mergeRefs(ref, containerRef)}
width={width}
height={height}
maxWidth={maxWidth}
diff --git a/packages/core/src/SideNav/XDSSideNav.tsx b/packages/core/src/SideNav/XDSSideNav.tsx
index b5509f7cdd..75ed4dae1c 100644
--- a/packages/core/src/SideNav/XDSSideNav.tsx
+++ b/packages/core/src/SideNav/XDSSideNav.tsx
@@ -26,7 +26,7 @@ import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {borderVars, colorVars, spacingVars} from '../theme/tokens.stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {XDSSideNavCollapseContext} from './XDSSideNavCollapseContext';
import {XDSSideNavCollapseButton} from './XDSSideNavCollapseButton';
import {useXDSSideNavRenderMode} from './XDSSideNavRenderContext';
@@ -454,14 +454,7 @@ export function XDSSideNav({
const navElement = (
<nav
- ref={node => {
- navRef.current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref) {
- ref.current = node;
- }
- }}
+ ref={mergeRefs(ref, navRef)}
role="navigation"
aria-label="Side navigation"
data-testid={testId}
diff --git a/packages/core/src/SideNav/XDSSideNavHeading.tsx b/packages/core/src/SideNav/XDSSideNavHeading.tsx
index b29fa4622c..b558d11336 100644
--- a/packages/core/src/SideNav/XDSSideNavHeading.tsx
+++ b/packages/core/src/SideNav/XDSSideNavHeading.tsx
@@ -19,7 +19,7 @@
* - /packages/cli/templates/blocks/components/SideNav/ (showcase blocks)
*/
-import {useCallback, useMemo, useRef, type ReactNode} from 'react';
+import {useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -39,7 +39,7 @@ import {navItemStyles} from '../NavItem/navItemStyles.stylex';
import {useXDSSideNavCollapse} from './XDSSideNavCollapseContext';
import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
import type {XDSLinkComponentType} from '../Link/types';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {useXDSMenuHover} from '../hooks/useXDSMenuHover';
import {XDSNavHeadingCloseContext} from '../NavMenu/XDSNavMenuContext';
@@ -356,28 +356,20 @@ export function XDSSideNavHeading({
[popover.hide],
);
- const {triggerProps, contentProps, menuRef, setTriggerEl} = useXDSMenuHover({
- show: popover.show,
- hide: popover.hide,
- isOpen: popover.isOpen,
- isEnabled: !!menu,
- showDelay: 0,
- });
+ const {triggerProps, contentProps, menuRef, setTriggerEl} =
+ useXDSMenuHover<HTMLDivElement>({
+ show: popover.show,
+ hide: popover.hide,
+ isOpen: popover.isOpen,
+ isEnabled: !!menu,
+ showDelay: 0,
+ });
- const setRef = useCallback(
- (el: HTMLDivElement | null) => {
- (rootRef as React.RefObject<HTMLDivElement | null>).current = el;
- setTriggerEl(el);
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- (ref as React.RefObject<HTMLDivElement | null>).current = el;
- }
- if (menu) {
- popover.triggerRef(el);
- }
- },
- [ref, popover, menu, setTriggerEl],
+ const setRef = mergeRefs<HTMLDivElement>(
+ rootRef,
+ setTriggerEl as React.Ref<HTMLDivElement>,
+ ref,
+ menu ? (popover.triggerRef as React.Ref<HTMLDivElement>) : undefined,
);
// In collapsed mode: hide if no icon, show icon-only if has icon
@@ -387,15 +379,10 @@ export function XDSSideNavHeading({
if (isCollapsed && icon) {
const collapsedIcon = <span {...stylex.props(styles.icon)}>{icon}</span>;
- const collapsedSetRef = (el: HTMLElement | null) => {
- (collapsedItemRef as React.RefObject<HTMLElement | null>).current = el;
- if (typeof ref === 'function') {
- ref(el as HTMLDivElement | null);
- } else if (ref) {
- (ref as React.RefObject<HTMLDivElement | null>).current =
- el as HTMLDivElement | null;
- }
- };
+ const collapsedSetRef = mergeRefs<HTMLElement>(
+ collapsedItemRef,
+ ref as React.Ref<HTMLElement>,
+ );
let collapsedElement: ReactNode;
@@ -440,7 +427,7 @@ export function XDSSideNavHeading({
</button>
{popover.render(
<div
- ref={menuRef as React.RefObject<HTMLDivElement>}
+ ref={menuRef}
role="menu"
{...stylex.props(styles.popoverContent)}
{...contentProps}>
@@ -632,7 +619,7 @@ export function XDSSideNavHeading({
</div>
{popover.render(
<div
- ref={menuRef as React.RefObject<HTMLDivElement>}
+ ref={menuRef}
role="menu"
{...stylex.props(styles.popoverContent)}
{...contentProps}>
@@ -692,7 +679,7 @@ export function XDSSideNavHeading({
</div>
{popover.render(
<div
- ref={menuRef as React.RefObject<HTMLDivElement>}
+ ref={menuRef}
role="menu"
{...stylex.props(styles.popoverContent)}
{...contentProps}>
diff --git a/packages/core/src/SideNav/XDSSideNavItem.tsx b/packages/core/src/SideNav/XDSSideNavItem.tsx
index ef83dceb69..d489ce9108 100644
--- a/packages/core/src/SideNav/XDSSideNavItem.tsx
+++ b/packages/core/src/SideNav/XDSSideNavItem.tsx
@@ -42,7 +42,7 @@ import {renderIconSlot, type XDSIconType} from '../Icon';
import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
import type {XDSLinkComponentType} from '../Link/types';
import {useXDSPopover} from '../Popover/useXDSPopover';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {XDSTooltip} from '../Tooltip';
import {navItemStyles, type NavItemSize} from '../NavItem/navItemStyles.stylex';
@@ -501,14 +501,7 @@ export function XDSSideNavItem({
return (
<div {...stylex.props(styles.root)}>
<button
- ref={el => {
- popover.triggerRef(el);
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- }}
+ ref={mergeRefs(ref, popover.triggerRef)}
type="button"
onClick={popover.toggle}
onMouseEnter={handlePopoverMouseEnter}
diff --git a/packages/core/src/Slider/XDSSlider.tsx b/packages/core/src/Slider/XDSSlider.tsx
index bcbf035799..d73545e8a1 100644
--- a/packages/core/src/Slider/XDSSlider.tsx
+++ b/packages/core/src/Slider/XDSSlider.tsx
@@ -38,7 +38,7 @@ import {
import {XDSField} from '../Field/XDSField';
import {XDSTooltip} from '../Tooltip/XDSTooltip';
import type {XDSInputStatus} from '../Field/types';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
// =============================================================================
@@ -747,15 +747,7 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
stylex.props(styles.sliderRow),
)}>
<div
- ref={node => {
- // Merge refs
- trackRef.current = node;
- if (typeof ref === 'function') {
- ref(node);
- } else if (ref) {
- ref.current = node;
- }
- }}
+ ref={mergeRefs(ref, trackRef)}
{...(isRange ? {role: 'group', 'aria-label': label} : undefined)}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
diff --git a/packages/core/src/TabList/XDSTabMenu.tsx b/packages/core/src/TabList/XDSTabMenu.tsx
index 74f4a4b9a8..0706d73cd1 100644
--- a/packages/core/src/TabList/XDSTabMenu.tsx
+++ b/packages/core/src/TabList/XDSTabMenu.tsx
@@ -34,7 +34,7 @@ import {useListFocus} from '../hooks/useListFocus';
import {useXDSTabListContext} from './XDSTabListContext';
import type {XDSTabListSize} from './XDSTabListContext';
import {tabScope} from './tab.markers.stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
export interface XDSTabMenuOption {
@@ -267,9 +267,10 @@ export function XDSTabMenu({
hasAutoFocus: false,
});
- const {listRef, handleKeyDown: handleListKeyDown} = useListFocus({
- onEscape: () => popover.hide(),
- });
+ const {listRef, handleKeyDown: handleListKeyDown} =
+ useListFocus<HTMLDivElement>({
+ onEscape: () => popover.hide(),
+ });
const handleToggle = useCallback(() => {
if (popover.isOpen) {
@@ -293,16 +294,9 @@ export function XDSTabMenu({
[tabListCtx, popover],
);
- const setButtonRef = useCallback(
- (el: HTMLButtonElement | null) => {
- popover.triggerRef(el);
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- (ref as React.MutableRefObject<HTMLButtonElement | null>).current = el;
- }
- },
- [popover, ref],
+ const setButtonRef = mergeRefs<HTMLButtonElement>(
+ popover.triggerRef as React.Ref<HTMLButtonElement>,
+ ref,
);
return (
@@ -355,7 +349,7 @@ export function XDSTabMenu({
</button>
{popover.render(
<div
- ref={listRef as React.RefObject<HTMLDivElement | null>}
+ ref={listRef}
id={menuId}
role="menu"
aria-label={label}
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
index 29d33fb74e..3bed4de1d3 100644
--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
@@ -40,11 +40,11 @@ import {
useMemo,
useSyncExternalStore,
type ReactNode,
- type Ref,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars} from '../../../theme/tokens.stylex';
import {XDSCheckboxInput} from '../../../CheckboxInput';
+import {mergeRefs} from '../../../utils';
import type {
TablePlugin,
XDSTableColumn,
@@ -125,26 +125,6 @@ function applyRowSelectionStyle(
}
}
-// =============================================================================
-// Ref Merging Utility
-// =============================================================================
-
-/**
- * Compose multiple refs into a single callback ref.
- * Used when multiple plugins need to attach refs to the same row.
- */
-function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): React.RefCallback<T> {
- return (el: T | null) => {
- for (const ref of refs) {
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref != null) {
- ref.current = el;
- }
- }
- };
-}
-
// =============================================================================
// Selection Context
// =============================================================================
diff --git a/packages/core/src/Text/XDSHeading.tsx b/packages/core/src/Text/XDSHeading.tsx
index 62696e6ef0..c9810cb649 100644
--- a/packages/core/src/Text/XDSHeading.tsx
+++ b/packages/core/src/Text/XDSHeading.tsx
@@ -16,7 +16,7 @@
* - /packages/cli/templates/blocks/components/Text/ (showcase blocks)
*/
-import {lazy, Suspense, useCallback, useRef, type ReactNode} from 'react';
+import {lazy, Suspense, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {
XDSTextColor,
@@ -39,7 +39,7 @@ import {
} from './text.stylex';
import {useTruncation} from './useTruncation';
import type {LayerPlacement} from '../Layer';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
const LazyXDSTooltip = lazy(() =>
@@ -229,30 +229,13 @@ export function XDSHeading({
// Ref for the heading element (used as tooltip anchor)
const headingRef = useRef<HTMLHeadingElement>(null);
- // Merge refs: ref, truncation.ref, headingRef
- const mergedRef = useCallback(
- (element: HTMLHeadingElement | null) => {
- // Forward ref
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- // Truncation ref
- truncation.ref(element);
- // Local ref for tooltip anchor
- headingRef.current = element;
- },
- [ref, truncation],
- );
-
// Build inline style for -webkit-line-clamp (dynamic value)
const inlineStyle = maxLines > 1 ? {WebkitLineClamp: maxLines} : undefined;
return (
<>
<Component
- ref={mergedRef}
+ ref={mergeRefs(ref, truncation.ref, headingRef)}
{...mergeProps(
xdsClassName('heading', {level, color, ...(type && {type})}),
stylex.props(
diff --git a/packages/core/src/Text/XDSText.tsx b/packages/core/src/Text/XDSText.tsx
index 672f90a54c..0435a560ed 100644
--- a/packages/core/src/Text/XDSText.tsx
+++ b/packages/core/src/Text/XDSText.tsx
@@ -16,7 +16,7 @@
* - /packages/cli/templates/blocks/components/Text/ (showcase blocks)
*/
-import {lazy, Suspense, useCallback, useRef, type ReactNode} from 'react';
+import {lazy, Suspense, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {
XDSTextType,
@@ -44,7 +44,7 @@ import {
} from './text.stylex';
import {useTruncation} from './useTruncation';
import type {LayerPlacement} from '../Layer';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
const LazyXDSTooltip = lazy(() =>
@@ -235,30 +235,13 @@ export function XDSText({
// Ref for the text element (used as tooltip anchor)
const textRef = useRef<HTMLElement>(null);
- // Merge refs: ref, truncation.ref, textRef
- const mergedRef = useCallback(
- (element: HTMLElement | null) => {
- // Forward ref
- if (typeof ref === 'function') {
- ref(element);
- } else if (ref) {
- ref.current = element;
- }
- // Truncation ref
- truncation.ref(element);
- // Local ref for tooltip anchor
- textRef.current = element;
- },
- [ref, truncation],
- );
-
// Build inline style for -webkit-line-clamp (dynamic value)
const inlineStyle = maxLines > 1 ? {WebkitLineClamp: maxLines} : undefined;
return (
<>
<Component
- ref={mergedRef}
+ ref={mergeRefs(ref, truncation.ref, textRef)}
{...mergeProps(
xdsClassName('text', {type, color: resolvedColor}),
stylex.props(
diff --git a/packages/core/src/TextArea/XDSTextArea.tsx b/packages/core/src/TextArea/XDSTextArea.tsx
index 78adb9d5ef..c65cf802c2 100644
--- a/packages/core/src/TextArea/XDSTextArea.tsx
+++ b/packages/core/src/TextArea/XDSTextArea.tsx
@@ -20,7 +20,6 @@ import {
useId,
useOptimistic,
useTransition,
- useCallback,
useRef,
type ChangeEvent,
type ClipboardEvent,
@@ -44,7 +43,7 @@ import {
} from '../Field';
import {XDSIcon, renderIconSlot, type XDSIconType} from '../Icon';
import {XDSSpinner} from '../Spinner';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {useInputContainer} from '../hooks/useInputContainer';
@@ -324,19 +323,6 @@ export function XDSTextArea({
const effectivelyDisabled = isDisabled || isBusy;
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLTextAreaElement | null) => {
- textareaRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
// Focus textarea when clicking anywhere on the wrapper (icons, padding, etc.)
const {onClick: handleWrapperClick, onMouseUp: handleWrapperMouseUp} =
useInputContainer({
@@ -387,7 +373,7 @@ export function XDSTextArea({
renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
<textarea
{...rest}
- ref={setRefs}
+ ref={mergeRefs(ref, textareaRef)}
id={id}
name={htmlName}
value={String(optimisticValue)}
diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsx
index bab8f55d40..e8a6646de0 100644
--- a/packages/core/src/TextInput/XDSTextInput.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.tsx
@@ -113,7 +113,7 @@ export type {
XDSInputStatus as XDSTextInputStatus,
XDSInputStatusType as XDSTextInputStatusType,
} from '../Field';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import {useXDSSize} from '../SizeContext/XDSSizeContext';
import {useInputContainer} from '../hooks/useInputContainer';
import {useXDSInputGroup} from '../InputGroup/XDSInputGroupContext';
@@ -317,19 +317,6 @@ export function XDSTextInput({
inputRef.current?.focus();
}, [onChange]);
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
// Focus input when clicking anywhere on the wrapper (icons, padding, etc.)
const {onClick: handleWrapperClick, onMouseUp: handleWrapperMouseUp} =
useInputContainer({
@@ -361,7 +348,7 @@ export function XDSTextInput({
{startIcon && renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
<input
{...rest}
- ref={setRefs}
+ ref={mergeRefs(ref, inputRef)}
id={id}
name={htmlName}
type={type}
diff --git a/packages/core/src/TimeInput/XDSTimeInput.tsx b/packages/core/src/TimeInput/XDSTimeInput.tsx
index bbcfd4def4..1ac35cc71d 100644
--- a/packages/core/src/TimeInput/XDSTimeInput.tsx
+++ b/packages/core/src/TimeInput/XDSTimeInput.tsx
@@ -58,6 +58,7 @@ import {
isTimeInRange,
xdsClassName,
mergeProps,
+ mergeRefs,
} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {useXDSSize} from '../SizeContext/XDSSizeContext';
@@ -492,19 +493,6 @@ export function XDSTimeInput({
inputRef.current?.focus();
}, [fireChange]);
- // Combine refs
- const setRefs = useCallback(
- (el: HTMLInputElement | null) => {
- inputRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- },
- [ref],
- );
-
// Focus input when clicking anywhere on the wrapper (icons, padding, etc.)
const {onClick: handleWrapperClick, onMouseUp: handleWrapperMouseUp} =
useInputContainer({
@@ -555,7 +543,7 @@ export function XDSTimeInput({
<XDSIcon icon="clock" size="sm" color="secondary" />
</div>
<input
- ref={setRefs}
+ ref={mergeRefs(ref, inputRef)}
id={id}
type="text"
value={displayValue}
diff --git a/packages/core/src/Timestamp/XDSTimestamp.tsx b/packages/core/src/Timestamp/XDSTimestamp.tsx
index e8ab809926..778e9cecc7 100644
--- a/packages/core/src/Timestamp/XDSTimestamp.tsx
+++ b/packages/core/src/Timestamp/XDSTimestamp.tsx
@@ -25,7 +25,7 @@ import type {
XDSTextColor,
XDSTextWeight,
} from '../theme/types';
-import {xdsClassName} from '../utils';
+import {xdsClassName, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
const LazyXDSTooltip = lazy(() =>
@@ -375,16 +375,6 @@ export function XDSTimestamp({
return () => clearInterval(timer);
}, [isLive, effectiveFormat, diffSeconds]);
- // Tooltip needs the ref
- const combinedRef = (el: HTMLTimeElement | null) => {
- timeRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- };
-
const showTooltip = hasTooltip && effectiveFormat === 'relative';
const timestampClass = xdsClassName('timestamp', {format: effectiveFormat});
@@ -399,7 +389,7 @@ export function XDSTimestamp({
className={[timestampClass, className].filter(Boolean).join(' ')}
style={style}>
<time
- ref={combinedRef}
+ ref={mergeRefs(ref, timeRef)}
dateTime={isoString}
aria-label={
effectiveFormat === 'relative' ? fullAbsoluteText : undefined
diff --git a/packages/core/src/Toolbar/XDSToolbar.tsx b/packages/core/src/Toolbar/XDSToolbar.tsx
index 3862d2a35e..3a93edbbc9 100644
--- a/packages/core/src/Toolbar/XDSToolbar.tsx
+++ b/packages/core/src/Toolbar/XDSToolbar.tsx
@@ -234,7 +234,7 @@ export function XDSToolbar({
const gapVar = spacingVars[spacingStepToVar[gap]] as string;
- const {listRef, handleKeyDown} = useListFocus({
+ const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({
itemSelector: 'button, input, [tabindex="0"]',
orientation,
});
@@ -250,7 +250,7 @@ export function XDSToolbar({
className={className}
style={style}>
<div
- ref={listRef as React.RefObject<HTMLDivElement>}
+ ref={listRef}
role="toolbar"
aria-label={label}
aria-orientation={orientation}
diff --git a/packages/core/src/Tooltip/XDSTooltip.tsx b/packages/core/src/Tooltip/XDSTooltip.tsx
index 61a6dc94cd..88a8a53877 100644
--- a/packages/core/src/Tooltip/XDSTooltip.tsx
+++ b/packages/core/src/Tooltip/XDSTooltip.tsx
@@ -182,7 +182,7 @@ export function XDSTooltip({
isOpen,
isDefaultOpen,
}: XDSTooltipProps): ReactElement {
- const wrapperRef = useRef<HTMLElement>(null);
+ const wrapperRef = useRef<HTMLDivElement>(null);
const textOnly = children != null ? isTextOnly(children) : false;
// Determine if hover indication should be shown
@@ -308,9 +308,7 @@ export function XDSTooltip({
// For element children: use display:contents, ref on first child
return (
<>
- <div
- ref={wrapperRef as React.RefObject<HTMLDivElement | null>}
- {...stylex.props(styles.wrapperContents)}>
+ <div ref={wrapperRef} {...stylex.props(styles.wrapperContents)}>
{children}
</div>
{tooltip.renderTooltip(content)}
diff --git a/packages/core/src/TopNav/XDSTopNavHeading.tsx b/packages/core/src/TopNav/XDSTopNavHeading.tsx
index 4ee0c57e51..6742731ca7 100644
--- a/packages/core/src/TopNav/XDSTopNavHeading.tsx
+++ b/packages/core/src/TopNav/XDSTopNavHeading.tsx
@@ -20,7 +20,7 @@
* - /packages/cli/templates/blocks/components/TopNav/ (showcase blocks)
*/
-import {useCallback, useMemo, useRef, type ReactNode} from 'react';
+import {useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -34,7 +34,7 @@ import {XDSLink} from '../Link';
import {getIcon} from '../Icon/globalIconRegistry';
import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
import type {XDSLinkComponentType} from '../Link/types';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {useXDSMenuHover} from '../hooks/useXDSMenuHover';
import {XDSNavHeadingCloseContext} from '../NavMenu/XDSNavMenuContext';
@@ -326,28 +326,20 @@ export function XDSTopNavHeading({
[popover.hide],
);
- const {triggerProps, contentProps, menuRef, setTriggerEl} = useXDSMenuHover({
- show: popover.show,
- hide: popover.hide,
- isOpen: popover.isOpen,
- isEnabled: !!menu,
- showDelay: 0,
- });
+ const {triggerProps, contentProps, menuRef, setTriggerEl} =
+ useXDSMenuHover<HTMLDivElement>({
+ show: popover.show,
+ hide: popover.hide,
+ isOpen: popover.isOpen,
+ isEnabled: !!menu,
+ showDelay: 0,
+ });
- const setRef = useCallback(
- (el: HTMLElement | null) => {
- rootRef.current = el;
- setTriggerEl(el);
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- if (menu) {
- popover.triggerRef(el);
- }
- },
- [ref, popover, menu, setTriggerEl],
+ const setRef = mergeRefs<HTMLElement>(
+ rootRef,
+ setTriggerEl as React.Ref<HTMLElement>,
+ ref,
+ menu ? (popover.triggerRef as React.Ref<HTMLElement>) : undefined,
);
const showChevron = !!menu;
@@ -503,7 +495,7 @@ export function XDSTopNavHeading({
</div>
{popover.render(
<div
- ref={menuRef as React.RefObject<HTMLDivElement>}
+ ref={menuRef}
role="menu"
{...stylex.props(styles.popoverContent)}
{...contentProps}>
@@ -566,7 +558,7 @@ export function XDSTopNavHeading({
</div>
{popover.render(
<div
- ref={menuRef as React.RefObject<HTMLDivElement>}
+ ref={menuRef}
role="menu"
{...stylex.props(styles.popoverContent)}
{...contentProps}>
diff --git a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
index 5758025eaf..583a87cc04 100644
--- a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
+++ b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
@@ -45,7 +45,7 @@ import {
import {useXDSPopover} from '../Popover/useXDSPopover';
import {XDSGrid} from '../Grid/XDSGrid';
import {getIcon} from '../Icon/globalIconRegistry';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {navItemStyles} from '../NavItem/navItemStyles.stylex';
import {useTopNavSlot} from './TopNavContext';
@@ -428,22 +428,10 @@ function DefaultMegaMenu({
};
}, [clearTimeouts]);
- const setButtonRef = useCallback(
- (el: HTMLButtonElement | null) => {
- triggerButtonRef.current = el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- (ref as React.MutableRefObject<HTMLButtonElement | null>).current = el;
- }
- },
- [ref],
- );
-
return (
<>
<button
- ref={setButtonRef}
+ ref={mergeRefs(triggerButtonRef, ref)}
type="button"
aria-haspopup="true"
aria-expanded={popover.isOpen}
diff --git a/packages/core/src/TopNav/XDSTopNavMenu.tsx b/packages/core/src/TopNav/XDSTopNavMenu.tsx
index 9d50d537bb..b253e267cb 100644
--- a/packages/core/src/TopNav/XDSTopNavMenu.tsx
+++ b/packages/core/src/TopNav/XDSTopNavMenu.tsx
@@ -15,18 +15,12 @@
* - /packages/cli/templates/blocks/components/TopNav/ (showcase blocks)
*/
-import React, {
- useCallback,
- useId,
- useRef,
- useState,
- type ReactNode,
-} from 'react';
+import React, {useId, useRef, useState, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {useXDSPopover} from '../Popover/useXDSPopover';
import {useXDSMenuHover} from '../hooks/useXDSMenuHover';
import {getIcon} from '../Icon/globalIconRegistry';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import {navItemStyles} from '../NavItem/navItemStyles.stylex';
import {useTopNavSlot} from './TopNavContext';
@@ -337,27 +331,21 @@ export function XDSTopNavMenu({
xstyle: styles.menuOffset,
});
- const {triggerProps, contentProps, menuRef, setTriggerEl} = useXDSMenuHover({
- show: popover.show,
- hide: popover.hide,
- isOpen: popover.isOpen,
- isEnabled: true,
- showDelay: delay,
- hideDelay,
- });
+ const {triggerProps, contentProps, menuRef, setTriggerEl} =
+ useXDSMenuHover<HTMLDivElement>({
+ show: popover.show,
+ hide: popover.hide,
+ isOpen: popover.isOpen,
+ isEnabled: true,
+ showDelay: delay,
+ hideDelay,
+ });
- const setTriggerRef = useCallback(
- (el: HTMLButtonElement | null) => {
- triggerButtonRef.current = el;
- popover.triggerRef(el);
- setTriggerEl(el);
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- (ref as React.MutableRefObject<HTMLButtonElement | null>).current = el;
- }
- },
- [popover, setTriggerEl, ref],
+ const setTriggerRef = mergeRefs<HTMLButtonElement>(
+ triggerButtonRef,
+ popover.triggerRef as React.Ref<HTMLButtonElement>,
+ setTriggerEl as React.Ref<HTMLButtonElement>,
+ ref,
);
// Mobile bar: hide menus entirely
@@ -444,7 +432,7 @@ export function XDSTopNavMenu({
</button>
{popover.render(
<div
- ref={menuRef as React.RefObject<HTMLDivElement>}
+ ref={menuRef}
role="menu"
aria-label={label}
{...contentProps}
diff --git a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
index 0397524ad4..12f4671a2d 100644
--- a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
@@ -39,7 +39,7 @@ import {
fontWeightVars,
typeScaleVars,
} from '../theme/tokens.stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs} from '../utils';
import type {XDSBaseProps} from '../XDSBaseProps';
import type {XDSSearchableItem, XDSSearchSource} from './types';
@@ -366,21 +366,6 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
}
}, [popover]);
- // Merge refs: forward ref + internal ref + fallback anchor ref
- const setInputRef = useCallback(
- (el: HTMLInputElement | null) => {
- (inputRef as React.RefObject<HTMLInputElement | null>).current = el;
- (fallbackAnchorRef as React.RefObject<HTMLInputElement | null>).current =
- el;
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- (ref as React.RefObject<HTMLInputElement | null>).current = el;
- }
- },
- [ref],
- );
-
// Set up anchor on the provided anchorRef or fall back to the input itself
useEffect(() => {
const el = anchorRef?.current ?? fallbackAnchorRef.current;
@@ -639,7 +624,7 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
return (
<>
<input
- ref={setInputRef}
+ ref={mergeRefs(ref, inputRef, fallbackAnchorRef)}
id={inputId}
type="text"
role="combobox"
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 38c1849524..7f7c37a19b 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -90,11 +90,11 @@ export interface UseFocusTrapOptions {
/**
* Return type for useFocusTrap hook
*/
-export interface UseFocusTrapReturn {
+export interface UseFocusTrapReturn<T extends HTMLElement = HTMLElement> {
/**
* Ref to attach to the container element that should trap focus.
*/
- containerRef: React.RefObject<HTMLElement | null>;
+ containerRef: React.RefObject<T | null>;
/**
* Focus the first focusable element in the container.
@@ -129,10 +129,12 @@ export interface UseFocusTrapReturn {
* </div>
* ```
*/
-export function useFocusTrap(options: UseFocusTrapOptions): UseFocusTrapReturn {
+export function useFocusTrap<T extends HTMLElement = HTMLElement>(
+ options: UseFocusTrapOptions,
+): UseFocusTrapReturn<T> {
const {isActive, onEscape} = options;
- const containerRef = useRef<HTMLElement | null>(null);
+ const containerRef = useRef<T | null>(null);
const lastFocusRef = useRef<Element | null>(null);
// Track if focus change was triggered by keyboard (Tab key)
const isKeyboardNavigationRef = useRef(false);
diff --git a/packages/core/src/hooks/useGridFocus.ts b/packages/core/src/hooks/useGridFocus.ts
index 0f2e2f61db..b9b63885a1 100644
--- a/packages/core/src/hooks/useGridFocus.ts
+++ b/packages/core/src/hooks/useGridFocus.ts
@@ -61,11 +61,11 @@ export interface UseGridFocusOptions {
/**
* Return type for useGridFocus hook
*/
-export interface UseGridFocusReturn {
+export interface UseGridFocusReturn<T extends HTMLElement = HTMLElement> {
/**
* Ref to attach to the grid container element.
*/
- gridRef: React.RefObject<HTMLElement | null>;
+ gridRef: React.RefObject<T | null>;
/**
* Key down handler to attach to the grid container.
@@ -112,7 +112,9 @@ export interface UseGridFocusReturn {
* </div>
* ```
*/
-export function useGridFocus(options: UseGridFocusOptions): UseGridFocusReturn {
+export function useGridFocus<T extends HTMLElement = HTMLElement>(
+ options: UseGridFocusOptions,
+): UseGridFocusReturn<T> {
const {
columns,
cellSelector = 'button:not([disabled]), [tabindex]:not([tabindex="-1"])',
@@ -122,7 +124,7 @@ export function useGridFocus(options: UseGridFocusOptions): UseGridFocusReturn {
onPageDown,
} = options;
- const gridRef = useRef<HTMLElement>(null);
+ const gridRef = useRef<T>(null);
/**
* Get all focusable cells in the grid.
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index 535d8374c7..1fc6796734 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -46,11 +46,11 @@ export interface UseListFocusOptions {
/**
* Return type for useListFocus hook
*/
-export interface UseListFocusReturn {
+export interface UseListFocusReturn<T extends HTMLElement = HTMLElement> {
/**
* Ref to attach to the list container element.
*/
- listRef: React.RefObject<HTMLElement | null>;
+ listRef: React.RefObject<T | null>;
/**
* Key down handler to attach to the list container.
@@ -94,9 +94,9 @@ export interface UseListFocusReturn {
* </div>
* ```
*/
-export function useListFocus(
+export function useListFocus<T extends HTMLElement = HTMLElement>(
options: UseListFocusOptions = {},
-): UseListFocusReturn {
+): UseListFocusReturn<T> {
const {
itemSelector = '[role="menuitem"]',
wrap = true,
@@ -104,7 +104,7 @@ export function useListFocus(
orientation = 'vertical',
} = options;
- const listRef = useRef<HTMLElement>(null);
+ const listRef = useRef<T>(null);
/**
* Get all focusable items in the list.
diff --git a/packages/core/src/hooks/useXDSMenuHover.ts b/packages/core/src/hooks/useXDSMenuHover.ts
index 3884fc05af..d61e0d54f0 100644
--- a/packages/core/src/hooks/useXDSMenuHover.ts
+++ b/packages/core/src/hooks/useXDSMenuHover.ts
@@ -35,7 +35,7 @@ interface UseXDSMenuHoverOptions {
hideDelay?: number;
}
-interface UseXDSMenuHoverReturn {
+interface UseXDSMenuHoverReturn<T extends HTMLElement = HTMLElement> {
triggerProps: {
onClick: () => void;
onMouseEnter: () => void;
@@ -46,14 +46,14 @@ interface UseXDSMenuHoverReturn {
onMouseLeave: () => void;
onKeyDown: (e: React.KeyboardEvent) => void;
};
- menuRef: React.RefObject<HTMLElement | null>;
+ menuRef: React.RefObject<T | null>;
focusFirst: () => void;
setTriggerEl: (el: HTMLElement | null) => void;
}
-export function useXDSMenuHover(
+export function useXDSMenuHover<T extends HTMLElement = HTMLElement>(
options: UseXDSMenuHoverOptions,
-): UseXDSMenuHoverReturn {
+): UseXDSMenuHoverReturn<T> {
const {
show,
hide,
@@ -95,7 +95,7 @@ export function useXDSMenuHover(
listRef: menuRef,
handleKeyDown: handleListKeyDown,
focusFirst,
- } = useListFocus({
+ } = useListFocus<T>({
onEscape: () => {
clearTimeouts();
hide();