Skip to content

Commit 42ba5dc

Browse files
authored
TreeView: Add custom aria label to TreeView.Item (#4617)
* Add custom aria label to TreeView.Item * Add changelog * Update hungry-rockets-smell.md
1 parent 2b22017 commit 42ba5dc

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

.changeset/hungry-rockets-smell.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@primer/react': minor
3+
---
4+
5+
Add an ability to provide custom `aria-label` and `aria-labelledby` to `TreeView.Item`

packages/react/src/TreeView/TreeView.test.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,30 @@ describe('Markup', () => {
4747
expect(items).toHaveLength(3)
4848
})
4949

50+
it('uses treeitem aria label', () => {
51+
const {queryAllByRole} = renderWithTheme(
52+
<>
53+
<TreeView>
54+
<TreeView.Item id="item-1" aria-label="Test tree item 1">
55+
Item 1
56+
</TreeView.Item>
57+
<TreeView.Item id="item-2" aria-labelledby="test-description">
58+
Item 2
59+
</TreeView.Item>
60+
<TreeView.Item id="item-2">Item 3</TreeView.Item>
61+
</TreeView>
62+
<span id="test-description">Tree item 2 description</span>
63+
</>,
64+
)
65+
66+
const items = queryAllByRole('treeitem')
67+
expect(items).toHaveLength(3)
68+
expect(items[0]).toHaveAccessibleName('Test tree item 1')
69+
expect(items[1]).toHaveAccessibleName('Tree item 2 description')
70+
expect(items[2]).toHaveAttribute('aria-labelledby')
71+
expect(items[2]).toHaveAccessibleName('Item 3')
72+
})
73+
5074
it('hides subtrees by default', () => {
5175
const {queryByRole} = renderWithTheme(
5276
<TreeView aria-label="Test tree">

packages/react/src/TreeView/TreeView.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,8 @@ Root.displayName = 'TreeView'
352352
// TreeView.Item
353353

354354
export type TreeViewItemProps = {
355+
'aria-label'?: React.AriaAttributes['aria-label']
356+
'aria-labelledby'?: React.AriaAttributes['aria-labelledby']
355357
id: string
356358
children: React.ReactNode
357359
containIntrinsicSize?: string
@@ -375,6 +377,8 @@ const Item = React.forwardRef<HTMLElement, TreeViewItemProps>(
375377
onSelect,
376378
children,
377379
className,
380+
'aria-label': ariaLabel,
381+
'aria-labelledby': ariaLabelledby,
378382
},
379383
ref,
380384
) => {
@@ -472,7 +476,8 @@ const Item = React.forwardRef<HTMLElement, TreeViewItemProps>(
472476
tabIndex={0}
473477
id={itemId}
474478
role="treeitem"
475-
aria-labelledby={labelId}
479+
aria-label={ariaLabel}
480+
aria-labelledby={ariaLabel ? undefined : ariaLabelledby || labelId}
476481
aria-describedby={`${leadingVisualId} ${trailingVisualId}`}
477482
aria-level={level}
478483
aria-expanded={isSubTreeEmpty ? undefined : isExpanded}

0 commit comments

Comments
 (0)