diff --git a/src/components/Tooltip/Tooltip.stories.tsx b/src/components/Tooltip/Tooltip.stories.tsx index 1726afa49c..5630f12798 100644 --- a/src/components/Tooltip/Tooltip.stories.tsx +++ b/src/components/Tooltip/Tooltip.stories.tsx @@ -29,11 +29,20 @@ Source: https://designsystem.digital.gov/components/tooltip/ }, }, }, + argTypes: { + id: { control: { type: 'text' } }, + }, +} + +type StorybookArgs = { + id: string } -export const TooltipDefault = (): React.ReactElement => ( +export const tooltipDefault = (args: StorybookArgs): React.ReactElement => (
- Default + + Default +
) diff --git a/src/components/Tooltip/Tooltip.test.tsx b/src/components/Tooltip/Tooltip.test.tsx index 5c56d5c99c..354a8f1b0d 100644 --- a/src/components/Tooltip/Tooltip.test.tsx +++ b/src/components/Tooltip/Tooltip.test.tsx @@ -25,8 +25,8 @@ describe('Tooltip component', () => { expect(wrapperEl).toHaveClass('usa-tooltip') const bodyEl = screen.queryByRole('tooltip', { hidden: true }) - expect(bodyEl).toBeInTheDocument() const tooltipId = bodyEl?.getAttribute('id') + expect(bodyEl).toBeInTheDocument() expect(bodyEl).toHaveAttribute('role', 'tooltip') expect(bodyEl).toHaveAttribute('aria-hidden', 'true') expect(bodyEl).toHaveTextContent('Click me') @@ -40,6 +40,20 @@ describe('Tooltip component', () => { expect(triggerEl).toHaveClass('usa-tooltip__trigger') }) + it('adds ID if given', () => { + const id = 'test-id' + render( + + My Tooltip + + ) + const bodyEl = screen.queryByRole('tooltip', { hidden: true }) + const tooltipId = bodyEl?.getAttribute('id') + expect(tooltipId).toBe(id) + const triggerEl = screen.queryByTestId('triggerElement') + expect(triggerEl).toHaveAttribute('aria-describedby', id) + }) + it('defaults the position to top if no position prop is given', () => { render(My Tooltip) diff --git a/src/components/Tooltip/Tooltip.tsx b/src/components/Tooltip/Tooltip.tsx index 4403ff2424..1f53a1494a 100644 --- a/src/components/Tooltip/Tooltip.tsx +++ b/src/components/Tooltip/Tooltip.tsx @@ -12,6 +12,7 @@ import classnames from 'classnames' import { isElementInViewport, calculateMarginOffset } from './utils' type TooltipProps = { + id?: string label: ReactNode title?: string position?: 'top' | 'bottom' | 'left' | 'right' | undefined @@ -56,7 +57,7 @@ export function Tooltip< const [wrapTooltip, setWrapTooltip] = useState(false) const [positionStyles, setPositionStyles] = useState({}) - const { position, wrapperclasses, className } = props + const { id = tooltipID.current, position, wrapperclasses, className } = props const positionTop = (e: HTMLElement, triggerEl: HTMLElement): void => { const topMargin = calculateMarginOffset('top', e.offsetHeight, triggerEl) @@ -214,7 +215,7 @@ export function Tooltip< ...customProps, ref: triggerElementRef, 'data-testid': 'triggerElement', - 'aria-describedby': tooltipID.current, + 'aria-describedby': id, tabIndex: 0, title: '', onMouseEnter: showTooltip, @@ -234,7 +235,7 @@ export function Tooltip<